package com.yanqu.road.server.manager.activity.rankunionwar.activity;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.activity.ActivityConditionInfo;
import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.rankunionwar.config.RankUnionWarConfig;
import com.yanqu.road.entity.activity.rankunionwar.config.RankUnionWarDivisionConfig;
import com.yanqu.road.entity.activity.rankunionwar.config.RankUnionWarFloorConfig;
import com.yanqu.road.entity.activity.rankunionwar.config.RankUnionWarTimeConfig;
import com.yanqu.road.entity.activity.rankunionwar.data.*;
import com.yanqu.road.entity.config.patrons.PatronsInfo;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.log.cross.CrossRankUnionWarCommandLog;
import com.yanqu.road.entity.log.cross.CrossRankUnionWarReviveLog;
import com.yanqu.road.entity.player.CrossUserBaseInfo;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.rank.stronghold.CrossActivityUnionRank;
import com.yanqu.road.entity.task.args.UnionRiseRankArgs;
import com.yanqu.road.entity.union.UnionBaseInfo;
import com.yanqu.road.logic.bussiness.activity.RankUnionWarBusiness;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.cross.CrossGeneralActivityUnionRankModel;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.logic.pb.UnionBasePb;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.RankUnionWarProto;
import com.yanqu.road.pb.cricket.CricketProto;
import com.yanqu.road.pb.manor.FishPondProto;
import com.yanqu.road.pb.vehicle.VehicleProto;
import com.yanqu.road.pb.worldmessage.WorldMessageProto;
import com.yanqu.road.server.CrossBattleServer;
import com.yanqu.road.server.manager.activity.CrossGeneralActivityRankMgr;
import com.yanqu.road.server.manager.activity.rankunionwar.CrossRankUnionWarDebugMgr;
import com.yanqu.road.server.manager.config.PatronsMgr;
import com.yanqu.road.server.manager.log.CrossActivityLogMgr;
import com.yanqu.road.server.manager.log.CrossAutoLogMgr;
import com.yanqu.road.server.manager.player.WorldMessageMgr;
import com.yanqu.road.server.manager.union.CrossUnionActivityDataMgr;
import com.yanqu.road.server.manager.union.CrossUnionReqContext;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.ConfigHelper;
import com.yanqu.road.utils.ListHelper;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;


public class CrossRankUnionWarActivity{

    private Logger logger = LogManager.getLogger(CrossRankUnionWarActivity.class.getName());

    private Map<Long,Object> lockMap = new ConcurrentHashMap<>();

    private RankUnionWarConfig config;

    private RandomHelper randomHelper = new RandomHelper();

    //战场编号
    private AtomicInteger makeGameNo = new AtomicInteger(1);

    //弹幕编号
    private AtomicLong barrageNo = new AtomicLong(1);
    //门客编号
    private AtomicInteger makePatronsNo = new AtomicInteger(1);

    /**
     * 活动总数据
     */
    private CrossRankUnionWarData crossRankUnionWarData;

    private Map<String, CrossRankUnionWarUnionData> unionDataMap;

    private Map<Long, CrossRankUnionWarUserLockData> userLockMap;


    //缓存用户商会信息，userBaseInfo不一定准确
    private Map<Long,String> userUnionIdMap = new ConcurrentHashMap<>();

    //还没结束的战斗，必须打的
    private Map<Integer,CrossRankUnionWarMatchData> battlingMatchMap = new ConcurrentHashMap<>();

    //所有的战斗
    private Map<Integer,CrossRankUnionWarMatchData> battleMatchMap = new ConcurrentHashMap<>();

    //竞猜列表 turn makeGameNo
    private Map<Integer,CrossRankUnionWarGambleData> gambleMap = new ConcurrentHashMap<>();

    //gameNo 弹幕列表
    private Map<Integer,List<CrossRankUnionWarBarrageData>> barrageList = new ConcurrentHashMap<>();

    //比赛信息 轮次，战场
    private Map<Integer, Map<Integer, List<CrossRankUnionWarMatchData>>> turnDivisionMatchMap = new ConcurrentHashMap<>();

    //比赛信息 战场 轮次 (没用了)
    private Map<Integer, Map<Integer, List<CrossRankUnionWarMatchData>>> divisionTurnMatchMap = new ConcurrentHashMap<>();

    private List<CrossRankUnionWarMatchData> needInsertMatchList = new ArrayList<>();
    private List<CrossRankUnionWarMatchData> needUpdateMatchList = new ArrayList<>();

    private List<CrossRankUnionWarLineData> needInsertLineList = new ArrayList<>();
    private List<CrossRankUnionWarLineData> needUpdateLineList = new ArrayList<>();

    private List<CrossRankUnionWarWaitPatronData> needInsertWaitPatronsList = new ArrayList<>();
    private List<CrossRankUnionWarWaitPatronData> needUpdateWaitPatronsList = new ArrayList<>();
    private List<CrossRankUnionWarWaitPatronData> needDelWaitPatronsList = new ArrayList<>();

    private List<CrossRankUnionWarBattlePatronData> needInsertBattlePatronsList = new ArrayList<>();
    private List<CrossRankUnionWarBattlePatronData> needUpdateBattlePatronsList = new ArrayList<>();

    private List<CrossRankUnionWarGambleData> needInsertGambleList = new ArrayList<>();
    private List<CrossRankUnionWarGambleData> needUpdateGambleList = new ArrayList<>();

    private List<CrossRankUnionWarUserLockData> needInsertUserLockList = new ArrayList<>();
    private List<CrossRankUnionWarUserLockData> needUpdateUserLockList = new ArrayList<>();

    private List<CrossRankUnionWarBarrageData> needInsertBarrageList = new ArrayList<>();
    private List<CrossRankUnionWarBarrageData> needUpdateBarrageList = new ArrayList<>();


    //新派遣上去要同步
    private List<CrossRankUnionWarMatchData> needSyncMatchCountList = new ArrayList<>();
    //出现比赛的输赢要同步
    private List<CrossRankUnionWarMatchData> needSyncMatchWinList = new ArrayList<>();
    //击杀消息同步
    private Map<Integer,List<CrossRankUnionWarNoticeData>> needSyncNoticeMap = new ConcurrentHashMap<>();
    //condition同步
    private Map<Long,List<CrossRankUnionConditionSyncData>> needSyncConditionMap = new ConcurrentHashMap<>();
    //弹幕同步
    private Map<Integer,List<CrossRankUnionWarBarrageData>> needSyncBarrageMap = new ConcurrentHashMap<>();


    //拉取战斗门客
    private int pagePatronsNum = 6;

    public CrossRankUnionWarActivity(ActivityInfo activityInfo) {

        Map<Integer, RankUnionWarTimeConfig> tempTimeConfigMap = RankUnionWarBusiness.getTimeConfigMap(activityInfo.getActivityId());
        Map<Integer, RankUnionWarDivisionConfig> tempDivisionConfigMap = RankUnionWarBusiness.getDivisionConfigMap(activityInfo.getActivityId());
        Map<Integer, RankUnionWarFloorConfig> tempFloorConfigMap = RankUnionWarBusiness.getFloorConfigMap(activityInfo.getActivityId());

        Map<String, ActivityConfig> activityConfigMap = ActivityBussiness.getActivityConfigMap(Collections.singletonList(activityInfo.getActivityId())).get(activityInfo.getActivityId());
        RankUnionWarConfig tempConfig = new RankUnionWarConfig();
        tempConfig.setActivityInfo(activityInfo);
        List<Integer> activityIdList = new ArrayList<>();
        activityIdList.add(activityInfo.getActivityId());
        Map<Integer, List<ActivityConditionInfo>> tempActivityConditionInfoMap = new ConcurrentHashMap<>();
        Map<Integer, Map<Integer, List<ActivityConditionInfo>>> tempActivityConditionTypeInfoMap = new ConcurrentHashMap<>();
        ActivityBussiness.getActivityConditionInfoMap(tempActivityConditionTypeInfoMap, tempActivityConditionInfoMap, activityIdList);
        tempConfig.setActivityConditionInfoList(tempActivityConditionInfoMap.get(activityInfo.getActivityId()));

        tempConfig.initConfig(activityConfigMap,tempTimeConfigMap,tempDivisionConfigMap,tempFloorConfigMap);
        config = tempConfig;


        // 【读取数据】

        crossRankUnionWarData = RankUnionWarBusiness.getCrossRankUnionWarData(getActivityId());
        if (crossRankUnionWarData == null) {
            crossRankUnionWarData = new CrossRankUnionWarData();
            crossRankUnionWarData.setActivityId(activityInfo.getActivityId());
            crossRankUnionWarData.setUnionGet(false);
            crossRankUnionWarData.setInsertOption();
        }
        unionDataMap = RankUnionWarBusiness.getCrossRankUnionWarUnionData(getActivityId());

        userLockMap = RankUnionWarBusiness.getUserLockList(getActivityId());

        initCacheUserUnionId();

        List<CrossRankUnionWarMatchData> battleMatchList = RankUnionWarBusiness.getMatchList(getActivityId());
        initBattleMatchList(battleMatchList);

        List<CrossRankUnionWarGambleData> gambleList = RankUnionWarBusiness.getGambleList(getActivityId());
        for(CrossRankUnionWarGambleData gambleData : gambleList){
            gambleMap.put(gambleData.getTurn(),gambleData);
        }

        makeGameNo = new AtomicInteger(RankUnionWarBusiness.getCrossRankUnionWarMaxGameNo(getActivityId()));
        makePatronsNo = new AtomicInteger(RankUnionWarBusiness.getCrossRankUnionWarMaxPatronsNo(getActivityId()));
        barrageNo = new AtomicLong(RankUnionWarBusiness.getCrossRankUnionWarBarrageNo(getActivityId()));
    }

    public void addBarrage(RankUnionWarProto.CrossRankUnionWarAddBarrageMsg reqMsg){
        long userId = reqMsg.getUserId();
        int gameNo = reqMsg.getGameNo();
        String content = reqMsg.getContent();
        CrossRankUnionWarMatchData gameMatch = getGameNoMatch(gameNo);
        if(gameMatch == null){
            return;
        }
        synchronized (barrageList){
            if(!barrageList.containsKey(gameNo)){
                barrageList.put(gameNo,new ArrayList<>());
            }
            CrossRankUnionWarBarrageData addData = new CrossRankUnionWarBarrageData();
            addData.setActivityId(getActivityId());
            addData.setBarrageNo(barrageNo.getAndIncrement());
            addData.setGameNo(gameNo);
            addData.setUserId(userId);
            addData.setContent(content);
            addData.setTime(System.currentTimeMillis());
            if(barrageList.get(gameNo).size() > 50){
                barrageList.get(gameNo).remove(0);
            }
            barrageList.get(gameNo).add(addData);

            if(!needSyncBarrageMap.containsKey(gameNo)){
                needSyncBarrageMap.put(gameNo,new ArrayList<>());
            }
            needSyncBarrageMap.get(gameNo).add(addData);
            addNeedInsertBarrage(addData);
        }
    }

    /**
     * 启动初始化一个玩家对应哪个门客的列表，用来找玩家的商会，玩家即使退出商会了也是属于这个比赛的商会的
     */
    private void initCacheUserUnionId(){
        if(unionDataMap.size() == 0 || !crossRankUnionWarData.isUnionGet()){
            return;
        }
        Map<Long,String> tempUserUnionIdMap = new ConcurrentHashMap<>();
        for(CrossRankUnionWarUnionData unionData : unionDataMap.values()){
            for(CrossRankUnionWarMemberData memberData : unionData.getMemberMap().values()){
                tempUserUnionIdMap.put(memberData.getUserId(),unionData.getUnionId());
            }
        }
        userUnionIdMap = tempUserUnionIdMap;
    }


    /**
     * 启动初始化比赛数据，加载比赛的派遣门客，战斗门客，线路
     * @param battleList
     */
    private void initBattleMatchList(List<CrossRankUnionWarMatchData> battleList){
        for(CrossRankUnionWarMatchData matchData : battleList){
            initWaitPatronsDb(matchData);
            initBattleLine(matchData);
            battleMatchMap.put(matchData.getGameNo(),matchData);
            if(!turnDivisionMatchMap.containsKey(matchData.getTurn())){
                turnDivisionMatchMap.put(matchData.getTurn(),new ConcurrentHashMap<>());
            }
            if(!turnDivisionMatchMap.get(matchData.getTurn()).containsKey(matchData.getDivision())){
                turnDivisionMatchMap.get(matchData.getTurn()).put(matchData.getDivision(),new ArrayList<>());
            }
            turnDivisionMatchMap.get(matchData.getTurn()).get(matchData.getDivision()).add(matchData);
            if(!divisionTurnMatchMap.containsKey(matchData.getDivision())){
                divisionTurnMatchMap.put(matchData.getDivision(),new ConcurrentHashMap<>());
            }
            if(!divisionTurnMatchMap.get(matchData.getDivision()).containsKey(matchData.getTurn())){
                divisionTurnMatchMap.get(matchData.getDivision()).put(matchData.getTurn(),new ArrayList<>());
            }
            divisionTurnMatchMap.get(matchData.getDivision()).get(matchData.getTurn()).add(matchData);
            if(matchData.getStatus() != 2){
                battlingMatchMap.put(matchData.getGameNo(),matchData);
            }
        }
    }


    /**
     * 启动初始化派遣门客数据
     * @param matchData
     */
    private void initWaitPatronsDb(CrossRankUnionWarMatchData matchData){
        if(matchData.getTurn() == crossRankUnionWarData.getGameTurn()) {
            List<CrossRankUnionWarWaitPatronData> waitPatronsDataList = RankUnionWarBusiness.getWaitPatronsList(matchData.getActivityId(),matchData.getGameNo());
            Map<Long, Map<Integer, CrossRankUnionWarWaitPatronData>> waitPatronMap = new ConcurrentHashMap<>(matchData.getWaitPatronsMap());
            for(CrossRankUnionWarWaitPatronData waitPatronData : waitPatronsDataList){
                if(!waitPatronMap.containsKey(waitPatronData.getUserId())){
                    waitPatronMap.put(waitPatronData.getUserId(),new ConcurrentHashMap<>());
                }
                waitPatronMap.get(waitPatronData.getUserId()).put(waitPatronData.getPatronId(),waitPatronData);
            }
            matchData.setWaitPatronsMap(waitPatronMap);
            sortLineSendPatrons(matchData);
        }
    }

    /**
     * 启动初始化线路数据
     * @param matchData
     */
    private void initBattleLine(CrossRankUnionWarMatchData matchData){
        Map<Integer,Map<String,Map<Integer,CrossRankUnionWarBattlePatronData>>> lineBattlePatronsMap = new ConcurrentHashMap<>();
        for(int line = 1; line <= 5; line++){
            Map<String,Map<Integer,CrossRankUnionWarBattlePatronData>> tempMap= new ConcurrentHashMap<>();
            tempMap.put(matchData.getUnionId1(),new ConcurrentHashMap<>());
            tempMap.put(matchData.getUnionId2(),new ConcurrentHashMap<>());
            lineBattlePatronsMap.put(line,tempMap);
        }
        if(matchData.getTurn() == crossRankUnionWarData.getGameTurn()){
            List<CrossRankUnionWarBattlePatronData> patronsList = RankUnionWarBusiness.getBattlePatronsList(matchData.getActivityId(),matchData.getGameNo());
            for(CrossRankUnionWarBattlePatronData battlePatronData : patronsList){
                Map<String,Map<Integer,CrossRankUnionWarBattlePatronData>> battlePatronsMap = lineBattlePatronsMap.get(battlePatronData.getLine());
                CrossRankUnionWarUnionData unionData = getUnionData(battlePatronData.getUserId());
                if(unionData == null)continue;
                if(!battlePatronsMap.containsKey(unionData.getUnionId())){
                    battlePatronsMap.put(unionData.getUnionId(),new ConcurrentHashMap<>());
                }
                battlePatronsMap.get(unionData.getUnionId()).put(battlePatronData.getLineIndex(),battlePatronData);
            }
        }

        Map<Integer, CrossRankUnionWarLineData> battleLineMap = new ConcurrentHashMap<>();
        List<CrossRankUnionWarLineData> lineDataList = RankUnionWarBusiness.getMatchLineList(matchData.getActivityId(),matchData.getGameNo());
        for(CrossRankUnionWarLineData lineData : lineDataList){
            lineData.setBattlePatronsMap(lineBattlePatronsMap.get(lineData.getLine()));
            battleLineMap.put(lineData.getLine(),lineData);
        }
        matchData.setBattleLineMap(battleLineMap);
    }


    public ActivityInfo getActivity(){
        return config.getActivityInfo();
    }

    public int getActivityId(){
        return config.getActivityInfo().getActivityId();
    }

    private synchronized Object getUserLock(long userId){
        if(!lockMap.containsKey(userId)){
            lockMap.put(userId,new Object());
        }
        return lockMap.get(userId);
    }

    /**
     * 派遣门客后加入定时同步门客数量给客户端
     * @param matchData
     */
    private void addNeedSyncMatchCountList(CrossRankUnionWarMatchData matchData){
        synchronized (needSyncMatchCountList){
            if(!needSyncMatchCountList.contains(matchData)){
                needSyncMatchCountList.add(matchData);
            }
        }
    }

    /**
     * 比赛线路或对局有胜利变化同步
     * @param matchData
     */
    private void addNeedSyncMatchWinList(CrossRankUnionWarMatchData matchData){
        synchronized (needSyncMatchWinList){
            if(!needSyncMatchWinList.contains(matchData)){
                needSyncMatchWinList.add(matchData);
            }
        }
    }

    /**
     * 门客击杀人数大于多少同步
     * @param noticeData
     */
    private void addNeedSyncNoticeMap(CrossRankUnionWarNoticeData noticeData){
        synchronized (needSyncNoticeMap){
            if(!needSyncNoticeMap.containsKey(noticeData.getGameNo())){
                needSyncNoticeMap.put(noticeData.getGameNo(),new ArrayList<>());
            }
            if(!needSyncNoticeMap.get(noticeData.getGameNo()).contains(noticeData)){
                needSyncNoticeMap.get(noticeData.getGameNo()).add(noticeData);
            }
        }
    }

    /**
     * 同步区服成就等condition触发
     * 1门客击杀人数,2进入赛场3，商会积分4，竞猜数据
     * @param conditionSyncData
     */
    private void addNeedSyncConditionMap(CrossRankUnionConditionSyncData conditionSyncData){
        synchronized (needSyncConditionMap){
            if(!needSyncConditionMap.containsKey(conditionSyncData.getUserId())){
                needSyncConditionMap.put(conditionSyncData.getUserId(),new ArrayList<>());
            }
            CrossRankUnionConditionSyncData removeData = null;
            List<CrossRankUnionConditionSyncData> userDataList = needSyncConditionMap.get(conditionSyncData.getUserId());
            boolean addFlag = true;
            for(CrossRankUnionConditionSyncData syncData : userDataList){
                //只有1类型和2类型同步一个就可以，其他全部都同步
                if(conditionSyncData.getType() == 1 || conditionSyncData.getType() == 2){
                    if(syncData.getType() == conditionSyncData.getType() && conditionSyncData.getValue().compareTo(syncData.getValue()) < 0){
                        removeData = syncData;
                        addFlag = false;
                    }
                }
            }
            if(addFlag){
                userDataList.add(conditionSyncData);
            }
            if(removeData != null){
                userDataList.remove(removeData);
            }
        }
    }

    /**
     * 开始处理商会自动报名，生成初始数据，去跨服拉取对应赚速前256门客回来
     * @param respMsg
     */
    public void backJoinUnion(RankUnionWarProto.CrossRankUnionWarGetMatchUnionRespMsg respMsg){
        if(crossRankUnionWarData.isUnionGet()){
            return;
        }
        logger.error(getActivityId()+"巅峰{}活动商会战拉取{}个商会来比赛",getActivityId(),respMsg.getUnionCount());
        Map<String, CrossRankUnionWarUnionData> tempUnionDataMap = new ConcurrentHashMap<>();
        for(RankUnionWarProto.RankUnionWarUnionMsg unionMsg : respMsg.getUnionList()){
            CrossRankUnionWarUnionData unionData = new CrossRankUnionWarUnionData();
            unionData.setActivityId(respMsg.getActivityId());
            unionData.setUnionId(unionMsg.getUnionUid());
            unionData.setUnionBaseInfo(UnionBasePb.parseUnionBaseInfo(unionMsg.getUnionInfo()));
            Map<Long, CrossRankUnionWarMemberData> memberMap = new ConcurrentHashMap<>();
            for(RankUnionWarProto.RankUnionWarUnionMemberMsg memberMsg : unionMsg.getMemberList()){
                CrossRankUnionWarMemberData memberData = new CrossRankUnionWarMemberData();
                memberData.setServerId(memberMsg.getServerId());
                memberData.setUserId(memberMsg.getUserId());
                memberData.setPosition(memberMsg.getPosition());
                memberMap.put(memberData.getUserId(),memberData);
            }
            unionData.setMemberMap(memberMap);
            unionData.setInsertOption();
            tempUnionDataMap.put(unionData.getUnionId(),unionData);
        }
        unionDataMap = tempUnionDataMap;
        crossRankUnionWarData.setUnionGet(true);
        initCacheUserUnionId();
        sendServerGetPatrons(1,true);
        sendUnionIdList();
    }

    /**
     * 每一轮比赛开始的时候拉一次商会信息更新下
     * @param respMsg
     */
    public void backUpdateUnion(RankUnionWarProto.CrossRankUnionWarGetMatchUnionRespMsg respMsg){
        int count = 0;
        logger.error("巅峰{}活动商会战来更新{}个商会信息",getActivityId(),respMsg.getUnionCount());
        for(RankUnionWarProto.RankUnionWarUnionMsg unionMsg : respMsg.getUnionList()){
            CrossRankUnionWarUnionData unionData = getUnionData(unionMsg.getUnionUid());
            if(unionData == null){
                continue;
            }
            unionData.setUnionBaseInfo(UnionBasePb.parseUnionBaseInfo(unionMsg.getUnionInfo()));
            count++;
        }
        logger.error("巅峰{}活动商会战更新成功{}个商会信息",getActivityId(),count);
    }

    /**
     * 玩家加入商会
     * @param reqMsg
     */
    public void joinUnion(RankUnionWarProto.CrossRankUnionWarGetPatronsRespMsg reqMsg) {
        long nowTime = System.currentTimeMillis();
        //比赛进行中
        if(nowTime/1000 >= getActivity().getEndTime()){
            return;
        }
        for(RankUnionWarProto.CrossRankUnionWarPatronsUpdateMsg userMsg : reqMsg.getUsersList()){
            UserBaseInfo userBaseInfo = PlayerBasePb.parseToUserBaseInfo(userMsg.getPlayerBaseData());
            CrossUserMgr.updateUserBaseInfoChange(userMsg.getUserId(),userBaseInfo);
            logger.info("巅峰{}活动商会{}玩家在备战期加入商会{}",getActivityId(),userMsg.getUserId(),userMsg.getUnionUid());
            CrossRankUnionWarUnionData unionData = getUnionData(userMsg.getUnionUid());
            if(unionData == null || unionData.isDie()){
                logger.info("巅峰{}商会加入成员，商会不存在或者已阵亡{},userId:{},isDie:{}",getActivityId(),userMsg.getUnionUid(),userMsg.getUserId(),unionData.isDie());
                continue;
            }
            Map<Long, CrossRankUnionWarMemberData> memberMap = unionData.getMemberMap();
            if(!memberMap.containsKey(userMsg.getUserId())){
                logger.info("巅峰{}玩家加入商会{},userId:{}玩家不是在活动前加入的",getActivityId(),userMsg.getUnionUid(),userMsg.getUserId());
                continue;
            }
            CrossRankUnionWarMemberData memberData = memberMap.get(userMsg.getUserId());
            if(!memberData.isQuit()){
                logger.info("巅峰{}玩家加入商会更新,玩家没有退出{},userId:{}",getActivityId(),userMsg.getUnionUid(),userMsg.getUserId());
                continue;
            }
            memberData.setQuit(false);
            unionData.setMemberMap(memberMap);
            CrossRankUnionWarMatchData matchData = getUnionMatch(userMsg.getUnionUid());
            if(matchData != null){
                synchronized (matchData){
                    if(matchData.getStatus() == 0){
                        addJoinUnionMatchWaitPatrons(matchData,unionData.getMemberMap().get(userMsg.getUserId()));
                    }
                }
            }
            changeUnionActivityValue(userMsg.getUnionUid(),UnionRiseRankArgs.NOTIFY_TYPE_NORMAL);
            syncUserData(memberData.getServerId(),memberData.getUserId());
        }
    }

    /**
     * 退出商会，移除门客，移除比赛击杀榜，移除管理员
     * @param reqMsg
     */
    public void quitUnion(RankUnionWarProto.CrossRankUnionWarQuitUnionSyncMsg reqMsg) {
        long nowTime = System.currentTimeMillis();
        //比赛进行中
        if(nowTime/1000 >= getActivity().getEndTime()){
            return;
        }
        for(RankUnionWarProto.CrossRankUnionWarQuitUnionMsg userMsg : reqMsg.getQuitList()){
            UserBaseInfo userBaseInfo = PlayerBasePb.parseToUserBaseInfo(userMsg.getPlayerBaseData());
            CrossUserMgr.updateUserBaseInfoChange(userMsg.getUserId(),userBaseInfo);
            logger.info("巅峰{}活动商会{}玩家在备战期加入商会{}",getActivityId(),userMsg.getUserId(),userMsg.getUnionUid());
            CrossRankUnionWarUnionData unionData = getUnionData(userMsg.getUnionUid());
            if(unionData == null || unionData.isDie()){
                logger.info("巅峰{}商会退出成员，没有对应比赛商会{},userId:{},isDie:{}",getActivityId(),userMsg.getUnionUid(),userMsg.getUserId(),unionData.isDie());
                continue;
            }
            Map<Long, CrossRankUnionWarMemberData> memberMap = unionData.getMemberMap();
            if(!memberMap.containsKey(userMsg.getUserId())){
                logger.info("巅峰{}商会退出更新,没有玩家{},userId:{}",getActivityId(),userMsg.getUnionUid(),userMsg.getUserId());
                continue;
            }
            CrossRankUnionWarMemberData memberData = memberMap.get(userMsg.getUserId());
            if(memberData.isQuit()){
                logger.info("巅峰{}商会退出更新,玩家已经退出{},userId:{}",getActivityId(),userMsg.getUnionUid(),userMsg.getUserId());
                continue;
            }
            //退出商会原先的职位就变成普通
            memberData.setPosition(eUnionPosition.Member.getValue());
            memberData.setQuit(true);
            unionData.setMemberMap(memberMap);
            CrossRankUnionWarMatchData matchData = getUnionMatch(userMsg.getUnionUid());
            if(matchData != null){
                synchronized (matchData){
                    //比赛进行中不移除门客继续打
                    if(matchData.getStatus() == 0){
                        removeQuitUnionMatchWaitPatrons(matchData,unionData.getMemberMap().get(userMsg.getUserId()));
                    }
                }
            }
            changeUnionActivityValue(userMsg.getUnionUid(),UnionRiseRankArgs.NOTIFY_TYPE_NORMAL);
            syncUserData(memberData.getServerId(),memberData.getUserId());
        }
    }

    /**
     * 玩家变动商会
     * @param reqMsg
     */
    public void positionUnion(RankUnionWarProto.CrossRankUnionWarPositionUnionSyncMsg reqMsg) {
        long nowTime = System.currentTimeMillis();
        //比赛进行中
        if(nowTime/1000 >= getActivity().getEndTime()){
            return;
        }
        for(RankUnionWarProto.CrossRankUnionWarPositionUnionMsg userMsg : reqMsg.getPositionList()){
            logger.info("巅峰{}活动商会{}玩家在备战期变更职位:商会{}",getActivityId(),userMsg.getUserId(),userMsg.getUnionUid());
            CrossRankUnionWarUnionData unionData = getUnionData(userMsg.getUnionUid());
            if(unionData == null){
                logger.info("巅峰{}变更职位成员，没有对应比赛商会{},userId:{},isDie:{}",getActivityId(),userMsg.getUnionUid(),userMsg.getUserId(),unionData == null?null:unionData.isDie());
                continue;
            }
            Map<Long, CrossRankUnionWarMemberData> memberMap = unionData.getMemberMap();
            if(!memberMap.containsKey(userMsg.getUserId())){
                logger.info("巅峰{}商会变更职位更新,没有玩家{},userId:{}",getActivityId(),userMsg.getUnionUid(),userMsg.getUserId());
                continue;
            }
            CrossRankUnionWarMemberData memberData = memberMap.get(userMsg.getUserId());
            if(memberData.isQuit()){
                logger.info("巅峰{}商会变更职位更新,玩家已经退出{},userId:{}",getActivityId(),userMsg.getUnionUid(),userMsg.getUserId());
                continue;
            }
            //变更的是会长把之前的会长卸掉
            if(userMsg.getPosition() == eUnionPosition.Master.getValue()){
                for(CrossRankUnionWarMemberData otherMemberData : memberMap.values()){
                    if(otherMemberData.getPosition() == eUnionPosition.Master.getValue()){
                        otherMemberData.setPosition(eUnionPosition.Member.getValue());
                    }
                }
            }
            memberData.setPosition(userMsg.getPosition());
            Map<Integer, Map<Integer, List<Long>>> opMap = unionData.getOpUserIdMap();
            CrossRankUnionWarMatchData matchData = getIngGameNoMatch(getMyGameNo(userMsg.getUserId()));
            //清除掉指挥官
            if(matchData != null){
                synchronized (matchData){
                    if(matchData.getStatus() == 0){
                        if(userMsg.getPosition() == eUnionPosition.Master.getValue() || userMsg.getPosition() == eUnionPosition.DeputyMaster.getValue()){
                            if(opMap.containsKey(matchData.getGameNo())){
                                for(int line : opMap.get(matchData.getGameNo()).keySet()){
                                    List<Long> opUserIdMap = opMap.get(matchData.getGameNo()).get(line);
                                    logger.error("巅峰{}商会玩家{}改变商会职位后变成会长副会长移除gameNo:{}比赛line:{}的指导员",getActivityId(),userMsg.getUserId(),matchData.getGameNo(),line);
                                    opUserIdMap.remove(memberData.getUserId());
                                }
                            }
                        }
                    }
                }
            }
            changeUnionActivityValue(userMsg.getUnionUid(),UnionRiseRankArgs.NOTIFY_TYPE_NORMAL);
            unionData.setOpUserIdMap(opMap);
            unionData.setMemberMap(memberMap);
        }
    }

    /**
     * 同步有哪些商会参赛了，游戏服上来拉取
     * @param serverId
     * @param reqMsg
     */
    public void sendUnionIdList(long serverId,RankUnionWarProto.CrossRankUnionWarGetUnionIdListReqMsg reqMsg) {
        RankUnionWarProto.CrossRankUnionWarGetUnionIdListRespMsg.Builder respMsg = RankUnionWarProto.CrossRankUnionWarGetUnionIdListRespMsg.newBuilder();
        if(reqMsg.getActivityId() == getActivityId()){
            respMsg.setActivityId(reqMsg.getActivityId());
            for(String unionId : unionDataMap.keySet()){
                RankUnionWarProto.CrossRankUnionWarUnionInfoMsg.Builder unionMsg = RankUnionWarProto.CrossRankUnionWarUnionInfoMsg.newBuilder();
                unionMsg.setUnionId(unionId);
                unionMsg.setIsDie(unionDataMap.get(unionId).isDie());
                respMsg.addUnion(unionMsg);
            }
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_CROSS_UNIONID_LIST, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, 0, pbMsg);
        }
    }

    /**
     * 同步所有区服有哪些商会参赛了，跨服自己同步下去
     */
    public void sendUnionIdList() {
        RankUnionWarProto.CrossRankUnionWarGetUnionIdListRespMsg.Builder respMsg = RankUnionWarProto.CrossRankUnionWarGetUnionIdListRespMsg.newBuilder();
        respMsg.setActivityId(getActivityId());
        for(String unionId : unionDataMap.keySet()){
            RankUnionWarProto.CrossRankUnionWarUnionInfoMsg.Builder unionMsg = RankUnionWarProto.CrossRankUnionWarUnionInfoMsg.newBuilder();
            unionMsg.setUnionId(unionId);
            unionMsg.setIsDie(unionDataMap.get(unionId).isDie());
            respMsg.addUnion(unionMsg);
        }

        for(long serverId : getActivity().getServerIdList()){
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_CROSS_UNIONID_LIST, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, 0, pbMsg);
        }
        logger.error("巅峰活动{}同步商会信息结束",getActivityId());
    }

    //输了没有参赛资格了同步
    public void sendUnionIdList(List<String> unionIdMap) {
        RankUnionWarProto.CrossRankUnionWarGetUnionIdListRespMsg.Builder respMsg = RankUnionWarProto.CrossRankUnionWarGetUnionIdListRespMsg.newBuilder();
        respMsg.setActivityId(getActivityId());
        for(String unionId : unionIdMap){
            if(unionDataMap.containsKey(unionId)){
                RankUnionWarProto.CrossRankUnionWarUnionInfoMsg.Builder unionMsg = RankUnionWarProto.CrossRankUnionWarUnionInfoMsg.newBuilder();
                unionMsg.setUnionId(unionId);
                unionMsg.setIsDie(unionDataMap.get(unionId).isDie());
                respMsg.addUnion(unionMsg);
            }
        }

        for(long serverId : getActivity().getServerIdList()){
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_CROSS_UNIONID_LIST, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, 0, pbMsg);
        }
    }

    //获取玩家的珍兽和鱼的锁
    private CrossRankUnionWarUserLockData getUserVFLock(long userId){
        CrossRankUnionWarUnionData unionData = getUnionData(userId);
        if(unionData == null){
            return null;
        }
        synchronized (userLockMap){
            if(!userLockMap.containsKey(userId)){
                CrossRankUnionWarUserLockData userLockData = new CrossRankUnionWarUserLockData();
                userLockData.setActivityId(getActivityId());
                userLockData.setUnionUid(unionData.getUnionId());
                userLockData.setUserId(userId);
                userLockData.setVehiclePatronsMap(new ConcurrentHashMap<>());
                userLockData.setFishPatronsMap(new ConcurrentHashMap<>());
                userLockData.setCricketPatronsMap(new ConcurrentHashMap<>());
                userLockMap.put(userLockData.getUserId(),userLockData);
                addNeedInsertUserLock(userLockData);
            }
        }
        return userLockMap.get(userId);
    }

    private Map<String, Integer> getUserVehiclePatronsMap(long userId){
        CrossRankUnionWarUserLockData userLockData = getUserVFLock(userId);
        if(userLockData == null){
            logger.error("巅峰商会{}没有玩家车宠数据返回空了1",getActivityId());
            return new ConcurrentHashMap<>();
        }
        return userLockData.getVehiclePatronsMap();
    }

    private Map<Integer,Integer> getUserFishPatronsMap(long userId){
        CrossRankUnionWarUserLockData userLockData = getUserVFLock(userId);
        if(userLockData == null){
            logger.error("巅峰商会{}没有玩家车宠数据返回空了2",getActivityId());
            return new ConcurrentHashMap<>();
        }
        return userLockData.getFishPatronsMap();
    }

    private Map<Integer,Integer> getUserCricketPatronsMap(long userId){
        CrossRankUnionWarUserLockData userLockData = getUserVFLock(userId);
        if(userLockData == null){
            logger.error("巅峰商会{}没有玩家昆虫数据返回空了3",getActivityId());
            return new ConcurrentHashMap<>();
        }
        return userLockData.getCricketPatronsMap();
    }

    public void activityVehicleTimes(long serverId, long userId, RankUnionWarProto.CrossVehicleActivityWarTimesReqMsg reqMsg) {
        VehicleProto.VehicleActivityWarTimesRespMsg.Builder respMsg = VehicleProto.VehicleActivityWarTimesRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setActivityId(reqMsg.getActivityId());
        respMsg.setActivityType(reqMsg.getActivityType());
        Map<String, Integer> vehiclePatronsMap = getUserVehiclePatronsMap(userId);
        for(VehicleProto.VehicleActivityWarTimesTempMsg timesMsg : reqMsg.getTimesList()){
            VehicleProto.VehicleActivityWarTimesTempMsg.Builder reBuilderMsg = timesMsg.toBuilder();
            String vehicleUid = timesMsg.getVehicleUid();
            if(vehiclePatronsMap.containsKey(vehicleUid)){
                reBuilderMsg.setWarTimes(1);
            }
            respMsg.addTimes(reBuilderMsg);
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_VEHICLE_ACTIVITY_WAR_TIMES, respMsg);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
    }

    public void activityFishTimes(long serverId, long userId, RankUnionWarProto.CrossFishActivityWarTimesReqMsg reqMsg) {
        FishPondProto.FishActivityWarTimesRespMsg.Builder respMsg = FishPondProto.FishActivityWarTimesRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setActivityId(reqMsg.getActivityId());
        respMsg.setActivityType(reqMsg.getActivityType());
        Map<Integer, Integer> fishPatronsMap = getUserFishPatronsMap(userId);
        for(FishPondProto.FishActivityWarTimesTempMsg timesMsg : reqMsg.getTimesList()){
            FishPondProto.FishActivityWarTimesTempMsg.Builder reBuilderMsg = timesMsg.toBuilder();
            int fishId = timesMsg.getFishId();
            if(fishPatronsMap.containsKey(fishId)){
                reBuilderMsg.setWarTimes(1);
            }
            respMsg.addTimes(reBuilderMsg);
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_FISH_ACTIVITY_WAR_TIMES, respMsg);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
    }

    public void activityCricketTimes(long serverId, long userId, RankUnionWarProto.CrossCricketActivityWarTimesReqMsg reqMsg) {
        CricketProto.CricketActivityWarTimesRespMsg.Builder respMsg = CricketProto.CricketActivityWarTimesRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setActivityId(reqMsg.getActivityId());
        respMsg.setActivityType(reqMsg.getActivityType());
        Map<Integer, Integer> cricketPatronsMap = getUserCricketPatronsMap(userId);
        for(CricketProto.CricketActivityWarTimesTempMsg timesMsg : reqMsg.getTimesList()){
            CricketProto.CricketActivityWarTimesTempMsg.Builder reBuilderMsg = timesMsg.toBuilder();
            int cricketId = timesMsg.getCricketId();
            if(cricketPatronsMap.containsKey(cricketId)){
                reBuilderMsg.setWarTimes(1);
            }
            respMsg.addTimes(reBuilderMsg);
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_CRICKET_ACTIVITY_WAR_TIMES, respMsg);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
    }

    //赚速排行榜
    public void unionEarnSpeedRank(long serverId, long userId, RankUnionWarProto.RankUnionWarUnionRankReqMsg reqMsg) {
        RankUnionWarProto.CrossRankUnionWarUnionEarnSpeedRankReqMsg.Builder builder = RankUnionWarProto.CrossRankUnionWarUnionEarnSpeedRankReqMsg.newBuilder();
        builder.setActivityId(getActivityId());
        List<Long> serverIdList = config.getActivityInfo().getServerIdList();
        builder.setEarnSpeedTopCount(config.getUnionCount());
        builder.addAllServerId(serverIdList);
        builder.setUserId(userId);
        builder.setUserServerId(serverId);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverIdList.get(randomHelper.next(0,serverIdList.size())), 0, YanQuMessageUtils.buildMessage(CrossProtocol.C3_CROSS_RANKUNIONWAR_UNION_EARNSPEED_RANK, builder));
    }


    //获取排行玩家
  public void getGambleUser(long serverId, long userId, RankUnionWarProto.RankUnionWarGetGambleUserReqMsg reqMsg) {
      RankUnionWarProto.RankUnionWarGetGambleUserRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarGetGambleUserRespMsg.newBuilder();
      respMsg.setCount(0);
      CrossRankUnionWarGambleData gambleData = gambleMap.get(reqMsg.getTurn());
      if(gambleData != null){
          if(gambleData.getRightUserMap().containsKey(reqMsg.getRight())){
              List<Long> userIdList = gambleData.getRightUserMap().get(reqMsg.getRight());
              respMsg.setCount(userIdList.size());
              int index = reqMsg.getIndex();
              int count = 0;
              for(int i = index ; i < userIdList.size();i++){
                  if(count == 10){
                      break;
                  }
                  long gambleUserId = userIdList.get(i);
                  UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(gambleUserId);
                  if(userBaseInfo == null)continue;
                  RankUnionWarProto.RankUnionWarGambleUserMsg.Builder userMsg = RankUnionWarProto.RankUnionWarGambleUserMsg.newBuilder();
                  userMsg.setUserId(gambleUserId);
                  userMsg.setNickName(userBaseInfo.getNickName());
                  userMsg.setServerId(userBaseInfo.getServerId());
                  userMsg.setIndex(i);
                  respMsg.addUser(userMsg);
                  count++;
              }
          }
      }
      YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_GET_GAMBLE_USER, respMsg);
      CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
    }


    public void inspireList(long serverId, long userId, RankUnionWarProto.RankUnionWarInspireListReqMsg reqMsg) {
        RankUnionWarProto.RankUnionWarInspireListRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarInspireListRespMsg.newBuilder();
        CrossRankUnionWarMatchData matchData = getGameNoMatch(reqMsg.getGameNo());
        CrossRankUnionWarUnionData unionData = getUnionData(reqMsg.getUnionId());
        if(matchData != null && unionData != null){
            Map<Long, CrossRankUnionWarMemberData> unionUserMap = unionData.getMemberMap();
            Map<Long, Integer> inspireTimesMap = matchData.getUserInspireTimesMap();
            for(long inspireUserId : inspireTimesMap.keySet()){
                if(unionUserMap.containsKey(inspireUserId)){
                    UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(inspireUserId);
                    if(userBaseInfo != null){
                        RankUnionWarProto.RankUnionWarUserInspireMsg.Builder userInspireMsg = RankUnionWarProto.RankUnionWarUserInspireMsg.newBuilder();
                        userInspireMsg.setUserId(inspireUserId);
                        userInspireMsg.setNickName(userBaseInfo.getNickName());
                        userInspireMsg.setTimes(inspireTimesMap.get(inspireUserId));
                        userInspireMsg.setPosition(unionUserMap.get(inspireUserId).getPosition());
                        userInspireMsg.setEarnSpeed(userBaseInfo.getEarnSpeed().toString());
                        respMsg.addUser(userInspireMsg);
                    }
                }
            }
            for(CrossRankUnionWarMemberData memberData : unionData.getMemberMap().values()){
                if(memberData != null && !memberData.isQuit() && !inspireTimesMap.containsKey(memberData.getUserId())){
                    UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(memberData.getUserId());
                    if(userBaseInfo != null){
                        RankUnionWarProto.RankUnionWarUserInspireMsg.Builder userInspireMsg = RankUnionWarProto.RankUnionWarUserInspireMsg.newBuilder();
                        userInspireMsg.setUserId(memberData.getUserId());
                        userInspireMsg.setNickName(userBaseInfo.getNickName());
                        userInspireMsg.setTimes(0);
                        userInspireMsg.setPosition(unionUserMap.get(memberData.getUserId()).getPosition());
                        userInspireMsg.setEarnSpeed(userBaseInfo.getEarnSpeed().toString());
                        respMsg.addUser(userInspireMsg);
                    }
                }
            }
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_INSPIRE_LIST, respMsg);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
    }

    //成员派遣门客列表
    public void sendPatronsUserList(long serverId, long userId, RankUnionWarProto.RankUnionWarSendPatronsUserListReqMsg reqMsg) {
        RankUnionWarProto.RankUnionWarSendPatronsUserListRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarSendPatronsUserListRespMsg.newBuilder();
        CrossRankUnionWarMatchData matchData = getGameNoMatch(reqMsg.getGameNo());
        CrossRankUnionWarUnionData unionData = getUnionData(reqMsg.getUnionId());
        if(matchData != null && unionData != null && matchData.getWaitPatronsMap() != null){
            for(CrossRankUnionWarMemberData memberData : unionData.getMemberMap().values()){
                if(!memberData.isQuit() && matchData.getWaitPatronsMap().containsKey(memberData.getUserId())){
                    UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(memberData.getUserId());
                    if(userBaseInfo == null)continue;
                    int sendCount = 0;
                    int allCount = 0;
                    for(CrossRankUnionWarWaitPatronData waitPatronData: matchData.getWaitPatronsMap().get(memberData.getUserId()).values()){
                        /*if(getPatronsWaitBattleTurn(waitPatronData.getUserId(),waitPatronData.getPatronId()) != 0){
                            continue;
                        }*/
                        if(isPatronsVehicleLock(waitPatronData)){
                            continue;
                        }
                        if(isPatronsFishLock(waitPatronData)){
                           continue;
                        }
                        if(isPatronsCricketLock(waitPatronData)){
                           continue;
                        }
                        if(waitPatronData.getLine() != 0){
                            sendCount++;
                        }
                        allCount++;
                    }
                    //五个职业满了不发了
                    if(sendCount == config.getBattleOccCount() * 5){
                        continue;
                    }
                    RankUnionWarProto.RankUnionWarPatronsUserSendMsg.Builder userMsg = RankUnionWarProto.RankUnionWarPatronsUserSendMsg.newBuilder();
                    userMsg.setUserId(memberData.getUserId());
                    userMsg.setNickName(userBaseInfo.getNickName());
                    userMsg.setSendCount(sendCount);
                    respMsg.addUser(userMsg);
                }
            }
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_SEND_PATRONS_USER_LIST, respMsg);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
    }

    public String getUserAreaParam(long userId) {
        int gameNo = getMyGameNo(userId);
        int division = getMyDivision(gameNo, userId);
        if (division == 0) {
            return null;
        }

        JSONObject json = new JSONObject();
        json.put("area", division);
        return json.toJSONString();
    }


    /**
     * 大到小排序,排名每场比赛的最高商会赚速，用来生成竞猜
     */
    class UnionGambleEarnSpeedSort implements Comparator<CrossRankUnionWarMatchData> {
        @Override
        public int compare(CrossRankUnionWarMatchData o1, CrossRankUnionWarMatchData o2) {
            CrossRankUnionWarUnionData o1unionData = getUnionData(o1.getUnionId1());
            CrossRankUnionWarUnionData o1unionData2 = getUnionData(o1.getUnionId2());
            if(o1unionData2 != null){
                if(o1unionData2.getUnionBaseInfo().getTotalEarnSpeed().compareTo(o1unionData.getUnionBaseInfo().getTotalEarnSpeed()) > 0){
                    o1unionData = o1unionData2;
                }
            }
            CrossRankUnionWarUnionData o2unionData = getUnionData(o2.getUnionId1());
            CrossRankUnionWarUnionData o2unionData2 = getUnionData(o2.getUnionId2());
            if(o2unionData2 != null){
                if(o2unionData2.getUnionBaseInfo().getTotalEarnSpeed().compareTo(o2unionData.getUnionBaseInfo().getTotalEarnSpeed()) > 0){
                    o2unionData = o2unionData2;
                }
            }
            if (o1unionData.getUnionBaseInfo().getTotalEarnSpeed().compareTo(o2unionData.getUnionBaseInfo().getTotalEarnSpeed()) == 0) {
                return 0;
            }
            if (o1unionData.getUnionBaseInfo().getTotalEarnSpeed().compareTo(o2unionData.getUnionBaseInfo().getTotalEarnSpeed()) > 0) {
                return -1;
            }
            return 1;
        }
    }

    /**
     * 从小到大，排名赚速绝对值差值比绝对值和大小 用来生成竞猜
     */
    class UnionGambleABSort implements Comparator<CrossRankUnionWarMatchData> {
        @Override
        public int compare(CrossRankUnionWarMatchData o1, CrossRankUnionWarMatchData o2) {
            BigDecimal value1 = BigDecimal.ZERO;
            BigDecimal value2 = BigDecimal.ZERO;
            CrossRankUnionWarUnionData o1unionData1 = getUnionData(o1.getUnionId1());
            CrossRankUnionWarUnionData o1unionData2 = getUnionData(o1.getUnionId2());
            if(o1unionData2 == null){
                value1 = BigDecimal.ONE;
            }else{
                value1 = (new BigDecimal(o1unionData1.getUnionBaseInfo().getTotalEarnSpeed())
                        .subtract(new BigDecimal(o1unionData2.getUnionBaseInfo().getTotalEarnSpeed())))
                        .divide((new BigDecimal(o1unionData1.getUnionBaseInfo().getTotalEarnSpeed())
                                .add(new BigDecimal(o1unionData2.getUnionBaseInfo().getTotalEarnSpeed()))), 10, BigDecimal.ROUND_HALF_EVEN).abs();
            }
            CrossRankUnionWarUnionData o2unionData1 = getUnionData(o2.getUnionId1());
            CrossRankUnionWarUnionData o2unionData2 = getUnionData(o2.getUnionId2());
            if(o2unionData2 == null){
                value2 = BigDecimal.ONE;
            }else{
                value2 = (new BigDecimal(o2unionData1.getUnionBaseInfo().getTotalEarnSpeed())
                        .subtract(new BigDecimal(o2unionData2.getUnionBaseInfo().getTotalEarnSpeed())))
                        .divide((new BigDecimal(o2unionData1.getUnionBaseInfo().getTotalEarnSpeed())
                                .add(new BigDecimal(o2unionData2.getUnionBaseInfo().getTotalEarnSpeed()))), 10, BigDecimal.ROUND_HALF_EVEN).abs();
            }
            if (value1.compareTo(value2) == 0) {
                return 0;
            }
            if (value1.compareTo(value2) > 0) {
                return 1;
            }
            return -1;
        }
    }

    //获取赛区前20名比赛来对战
    //例如：第一轮只开放青铜赛区，则在青铜赛区中的排名前20的商会对战中，筛选出3场上阵门客能力总和最近的3场比赛进行竞猜。
    //在第7轮或第8轮时，由于最高赛区中的比赛数量不足竞猜数，则在对应最高赛区读取所有比赛进行竞猜后，再从下面的赛区中读取对应数量比赛进行补
    //例如第8轮是巅峰决赛，则会将决赛取出，然后从王者赛区也会抽取对应的相近最近的2场比赛，进行竞猜
    private List<CrossRankUnionWarMatchData> getTop20Match(List<CrossRankUnionWarMatchData> matchList){
        int topLong = config.getGambleRankTop();
        List<CrossRankUnionWarMatchData> top20matchList = new ArrayList<>();
        matchList.sort(new UnionGambleEarnSpeedSort());
        for(int i = 0;i < topLong; i++){
            if(i < matchList.size()){
                top20matchList.add(matchList.get(i));
            }else{
                break;
            }
        }
        return top20matchList;
    }

    /**
     * 生成竞猜的比赛
     * @param turn
     */
    private void randomGambleTurn(int turn){
        if(gambleMap.containsKey(turn)){
            return;
        }
        CrossRankUnionWarGambleData gambleData = new CrossRankUnionWarGambleData();
        gambleData.setActivityId(getActivityId());
        gambleData.setTurn(turn);
        Map<Integer,List<String>> turnGambleGameNoMap = new ConcurrentHashMap<>();
        Map<Integer, List<CrossRankUnionWarMatchData>> divisionMap = turnDivisionMatchMap.get(turn);
        List<Integer> divisionList = new ArrayList<>(divisionMap.keySet());
        Collections.sort(divisionList);
        Collections.reverse(divisionList);
        int makeGambleCount = config.getGambleCount();
        for(int divisionId : divisionList){
            List<CrossRankUnionWarMatchData> matchList = new ArrayList<>(divisionMap.get(divisionId));
            List<CrossRankUnionWarMatchData> top20matchList = getTop20Match(matchList);
            top20matchList.sort(new UnionGambleABSort());
            while (top20matchList.size() > 0 && makeGambleCount > 0){
                CrossRankUnionWarMatchData matchData = top20matchList.get(0);
                if(StringUtils.isNullOrEmpty(matchData.getUnionId2())){
                    top20matchList.remove(matchData);
                    continue;
                }
                List<String> unionIdList = new ArrayList<>();
                unionIdList.add(matchData.getUnionId2());
                unionIdList.add(matchData.getUnionId1());
                turnGambleGameNoMap.put(matchData.getGameNo(),unionIdList);
                makeGambleCount--;
                top20matchList.remove(matchData);
            }
        }
        gambleData.setGameNoMap(turnGambleGameNoMap);
        addNeedInsertGamble(gambleData);
        gambleMap.put(turn,gambleData);
    }

    /**
     * 竞猜优化成每个赛区选一个
     * @param turn
     */
    private void randomGambleTurn2(int turn){
        if(gambleMap.containsKey(turn)){
            return;
        }
        CrossRankUnionWarGambleData gambleData = new CrossRankUnionWarGambleData();
        gambleData.setActivityId(getActivityId());
        gambleData.setTurn(turn);
        Map<Integer,List<String>> turnGambleGameNoMap = new ConcurrentHashMap<>();
        Map<Integer, List<CrossRankUnionWarMatchData>> divisionMap = turnDivisionMatchMap.get(turn);
        List<Integer> divisionList = new ArrayList<>(divisionMap.keySet());
        Collections.sort(divisionList);
        Collections.reverse(divisionList);
        int makeGambleCount = config.getGambleCount();
        //每个战区取多少个比赛出来，遇到没有比赛直接跳过
        Map<Integer,Integer> divisionNumMap = new ConcurrentHashMap<>();
        while (divisionList.size() > 0 && makeGambleCount > 0){
            if(makeGambleCount > 4){
                divisionNumMap.put(divisionList.get(0),makeGambleCount - 3);
                makeGambleCount = 3;
            }else{
                divisionNumMap.put(divisionList.get(0),1);
                makeGambleCount--;
            }
            divisionList.remove(0);
        }

        for(int divisionId : divisionNumMap.keySet()){
            int makeCount = divisionNumMap.get(divisionId);
            List<CrossRankUnionWarMatchData> matchList = new ArrayList<>(divisionMap.get(divisionId));
            List<CrossRankUnionWarMatchData> top20matchList = getTop20Match(matchList);
            top20matchList.sort(new UnionGambleABSort());
            while (top20matchList.size() > 0 && makeCount > 0){
                CrossRankUnionWarMatchData matchData = top20matchList.get(0);
                if(StringUtils.isNullOrEmpty(matchData.getUnionId2())){
                    top20matchList.remove(matchData);
                    continue;
                }
                List<String> unionIdList = new ArrayList<>();
                unionIdList.add(matchData.getUnionId2());
                unionIdList.add(matchData.getUnionId1());
                turnGambleGameNoMap.put(matchData.getGameNo(),unionIdList);
                makeCount--;
                top20matchList.remove(matchData);
            }
        }
        gambleData.setGameNoMap(turnGambleGameNoMap);
        addNeedInsertGamble(gambleData);
        gambleMap.put(turn,gambleData);
    }

    /**
     * 检测每一轮的门客同步上来了没，没有同步上来就发送请求到区服拉取，拉取成功会记录
     * @param turn
     * @return
     */
    private boolean checkMemberPatronsList(int turn){
        boolean allGet = true;
        for(CrossRankUnionWarUnionData unionData : unionDataMap.values()){
            synchronized (unionData){
                for(CrossRankUnionWarMemberData memberData : unionData.getMemberMap().values()){
                    if(!memberData.getPatronDataMap().containsKey(turn)){
                        logger.error("巅峰{}活动第{}轮校验数据{}商会，商会id{},的成员{},没有获取到门客发送请求去拉取",
                                getActivityId(),turn,unionData.getUnionBaseInfo().getUnionName(),unionData.getUnionId(),memberData.getUserId());
                        if(memberData.getIsGetPatronsMap().contains(turn)){
                            logger.error("巅峰已经拉取过门客了，门客数据不存在");
                        }else{
                            if(System.currentTimeMillis()/1000 > config.getActivityInfo().getBeginTime()){
                                sendGetAllPatrons(unionData,turn);
                            }
                        }
                        allGet = false;
                    }
                }
            }
        }
        return allGet;
    }

    /**
     * 生成比赛数据
     */
    private void makeTurnBattle(){
        //数据还么准备好不能开始创
        if(!crossRankUnionWarData.isUnionGet()){
            return;
        }
        int nowTurn = crossRankUnionWarData.getGameTurn();
        int nextTurn = nowTurn + 1;
        //都打完了
        if(nowTurn >= config.getLastTimeConfig().getTimeId()){
            return;
        }
        if(nowTurn == 0){
            if(!checkMemberPatronsList(nextTurn))return;
            List<String> allUnionList = new ArrayList<>();
            for(CrossRankUnionWarUnionData unionData : unionDataMap.values()){
                allUnionList.add(unionData.getUnionId());
            }
            //一开始多有人都在同一个段位打
            RankUnionWarTimeConfig timeConfig = config.getTimeConfig(nextTurn);
            Map<Integer,List<String>> divisionMap = new ConcurrentHashMap<>();
            divisionMap.put(timeConfig.getTimeId(),allUnionList);
            Map<Integer, Map<Integer, List<String>>>  battleUnionIdMap = crossRankUnionWarData.getBattleUnionIdMap();
            battleUnionIdMap.put(nextTurn,divisionMap);
            crossRankUnionWarData.setBattleUnionIdMap(battleUnionIdMap);
            //生成对战
            makeTurnBattle(nextTurn,divisionMap);
            //生成竞猜
            randomGambleTurn(nextTurn);
            crossRankUnionWarData.setGameTurn(nextTurn);
            syncUserDataGameNew();
            logger.error("巅峰{}生成第一场比赛成功",getActivityId());
        }else{
            //上一局的数据都清掉了再开始生成，生成下一场的晋级淘汰队伍
            if(battlingMatchMap.size() == 0){
                RankUnionWarTimeConfig timeConfig = config.getTimeConfig(System.currentTimeMillis());
                //当前时间已经到达什么场次了，中间可能因为维护错过了，中间的场次也会快速生成并且自动比赛结束
                if(timeConfig != null && timeConfig.getSession() >= nowTurn){
                    Map<Integer, Map<Integer, List<String>>>  battleUnionIdMap = crossRankUnionWarData.getBattleUnionIdMap();
                    Map<Integer, List<String>> divisionMap = battleUnionIdMap.get(nextTurn);
                    //没有下一场的对局数据
                    if(divisionMap == null || !checkMemberPatronsList(nextTurn))return;
                    makeTurnBattle(nextTurn,divisionMap);
                    randomGambleTurn(nextTurn);
                    crossRankUnionWarData.setGameTurn(nextTurn);
                    syncUserDataGameNew();
                    sendUpdateUnionMsg();
                    logger.error("巅峰{}生成第{}场比赛成功",getActivityId(),nextTurn);
                }
            }
        }
    }

    //又优化了。。。。
    private void makeTurnBattle2(){
        //数据还么准备好不能开始创
        if(!crossRankUnionWarData.isUnionGet()){
            return;
        }
        int nowTurn = crossRankUnionWarData.getGameTurn();
        int nextTurn = nowTurn + 1;
        //都打完了
        if(nowTurn >= config.getLastTimeConfig().getTimeId()){
            return;
        }
        if(nowTurn == 0){
            if(!checkMemberPatronsList(nextTurn))return;
            List<CrossRankUnionWarUnionData> allUnionList = new ArrayList<>(unionDataMap.values());
            allUnionList.sort(new UnionEarnSpeedSort());
            //变成每个赛区都有了，不是全部青铜了
            Map<Integer, Integer> divisionNumMap = config.getDivisionNumMap();
            List<Integer> divisionIdList = new ArrayList<>(divisionNumMap.keySet());
            Collections.sort(divisionIdList);
            Collections.reverse(divisionIdList);
            Map<Integer,List<String>> divisionMap = new ConcurrentHashMap<>();
            for(int divisionId : divisionIdList){
                int num = divisionNumMap.get(divisionId);
                divisionMap.put(divisionId,new ArrayList<>());
                while (divisionMap.get(divisionId).size() < num && allUnionList.size() > 0){
                    divisionMap.get(divisionId).add(allUnionList.get(0).getUnionId());
                    allUnionList.remove(0);
                }
            }
            Map<Integer, Map<Integer, List<String>>>  battleUnionIdMap = crossRankUnionWarData.getBattleUnionIdMap();
            battleUnionIdMap.put(nextTurn,divisionMap);
            crossRankUnionWarData.setBattleUnionIdMap(battleUnionIdMap);
            //生成对战
            makeTurnBattle2(nextTurn,divisionMap);
            //生成竞猜
            randomGambleTurn2(nextTurn);
            crossRankUnionWarData.setGameTurn(nextTurn);
            syncUserDataGameNew();
            logger.error("巅峰{}生成第一场比赛成功",getActivityId());
        }else{
            //上一局的数据都清掉了再开始生成，生成下一场的晋级淘汰队伍
            if(battlingMatchMap.size() == 0){
                RankUnionWarTimeConfig timeConfig = config.getTimeConfig(System.currentTimeMillis());
                //当前时间已经到达什么场次了，中间可能因为维护错过了，中间的场次也会快速生成并且自动比赛结束
                if(timeConfig != null && timeConfig.getSession() >= nowTurn){
                    Map<Integer, Map<Integer, List<String>>>  battleUnionIdMap = crossRankUnionWarData.getBattleUnionIdMap();
                    Map<Integer, List<String>> divisionMap = battleUnionIdMap.get(nextTurn);
                    //没有下一场的对局数据
                    if(divisionMap == null || !checkMemberPatronsList(nextTurn))return;
                    makeTurnBattle2(nextTurn,divisionMap);
                    randomGambleTurn2(nextTurn);
                    crossRankUnionWarData.setGameTurn(nextTurn);
                    syncUserDataGameNew();
                    sendUpdateUnionMsg();
                    logger.error("巅峰{}生成第{}场比赛成功",getActivityId(),nextTurn);
                }
            }
        }
    }

    /**
     * 游戏新开始同步信息给有资格的玩家
     */
    private void syncUserDataGameNew(){
        Map<Long,List<RankUnionWarProto.RankUnionWarCrossUserDataSyncMsg.Builder>> syncServerIdMap = new ConcurrentHashMap<>();
        for(CrossRankUnionWarUnionData unionData : unionDataMap.values()){
            for(CrossRankUnionWarMemberData memberData : unionData.getMemberMap().values()){
                if(!syncServerIdMap.containsKey(memberData.getServerId())){
                    syncServerIdMap.put(memberData.getServerId(),new ArrayList<>());
                }
                RankUnionWarProto.RankUnionWarCrossUserDataSyncMsg.Builder crossSyncDataMsg = RankUnionWarProto.RankUnionWarCrossUserDataSyncMsg.newBuilder();
                crossSyncDataMsg.setUserId(memberData.getUserId());
                crossSyncDataMsg.setSyncData(parseUserData(memberData.getUserId()));
                syncServerIdMap.get(memberData.getServerId()).add(crossSyncDataMsg);
            }
        }
        for(long serverId : syncServerIdMap.keySet()){
            //怕包太大了，十个十个来
            int sendIndex = 0;
            RankUnionWarProto.RankUnionWarNewGameSyncMsg.Builder serverSyncMsg = RankUnionWarProto.RankUnionWarNewGameSyncMsg.newBuilder();
            for(RankUnionWarProto.RankUnionWarCrossUserDataSyncMsg.Builder syncMsg : syncServerIdMap.get(serverId)){
                serverSyncMsg.addSyncData(syncMsg);
                sendIndex++;
                //不报msg length的最大个数了
                if(sendIndex >= 1000){
                    RankUnionWarProto.RankUnionWarNewGameSyncMsg.Builder tempSyncMsg = serverSyncMsg;
                    YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_CROSS_SYNC_USER_DATA, tempSyncMsg);
                    CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, 0, pbMsg);
                    sendIndex = 0;
                    serverSyncMsg = RankUnionWarProto.RankUnionWarNewGameSyncMsg.newBuilder();
                }
            }
            if(serverSyncMsg.getSyncDataCount() > 0){
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_CROSS_SYNC_USER_DATA, serverSyncMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, 0, pbMsg);
            }
        }
    }

    /**
     * 如果当前是战斗时间就开始战斗
     */
    public void matchProcess(){
        long nowTime = System.currentTimeMillis();
        for(CrossRankUnionWarMatchData battleMatch : battlingMatchMap.values()){
            synchronized (battleMatch){
                if(battleMatch.getStatus() == 1){
                    //这里不用锁了，战斗中只有门客复活会冲突，里面有了
                    battleMatch2(battleMatch,nowTime);
                }
            }
            RankUnionWarTimeConfig timeConfig = config.getTimeConfig(battleMatch.getTurn());
            //提前一分钟就全部拉去匹配
            if(nowTime > timeConfig.getStartTime() && battleMatch.getStatus() == 0){
                //等待中变成进行中
                //变成进行中的战斗要把玩家没有派遣的门客按照每条路线一比一随机派遣上去
                //策划出了个优化，逻辑完全改乱了
                //会和玩家的出入商会并发，最后几秒导致比赛开始了还在插备战门客，这时候备战门客被拉出战
                synchronized (battleMatch){
                    int channelId = ConfigHelper.getInt("channelId");
                    if(channelId == 666777888){
                        battleStatueGoingVersionDebug(battleMatch);
                    }else{
                        battleStatueGoingVersion4(battleMatch);
                    }
                }
            }else if(nowTime > timeConfig.getEndTime() && battleMatch.getStatus() == 1){
                //进行中变结束
                //变结束要判断谁胜利了，谁胜利的路线多就胜利了，平局就开始比杀敌数，杀敌数要加上存货门客，一个门客算一个杀敌数
                //结束了要去生成下一轮的比赛数据了
                synchronized (battleMatch){
                    battleStatueOver2(battleMatch);
                    if(battlingMatchMap.size() == 0 && crossRankUnionWarData.getGameTurn() != 0){
                        logger.error("巅峰活动{},轮次{},结束当轮比赛",getActivityId(),crossRankUnionWarData.getGameTurn());
                        endTurn(crossRankUnionWarData.getGameTurn());
                        sendUnionIdList();
                    }
                }
            }
        }
    }

    /**
     * 进入战斗状态策划改版2
     * @param battleMatch
     */
    private void battleStatueGoingVersion2(CrossRankUnionWarMatchData battleMatch){
        logger.error("巅峰{}比赛gameNo:{}进入进行状态",getActivityId(),battleMatch.getGameNo());
        //没有派遣的自动给他派遣的列表;
        Map<Integer,Map<Integer,CrossRankUnionWarWaitPatronData>> linePatronsMap = new ConcurrentHashMap<>();
        for(int line = 1;line <= 5;line++){
            linePatronsMap.put(line,new ConcurrentHashMap<>());
        }
        Map<Integer, CrossRankUnionWarLineData> battleLineMap = battleMatch.getBattleLineMap();
        List<CrossRankUnionWarWaitPatronData> needAutoSendUnion1Patrons = new ArrayList<>();
        List<CrossRankUnionWarWaitPatronData> needAutoSendUnion2Patrons = new ArrayList<>();
        Map<Long, Map<Integer, CrossRankUnionWarWaitPatronData>> waitPatronsMap = new ConcurrentHashMap<>(battleMatch.getWaitPatronsMap());
        for(long userId : waitPatronsMap.keySet()){
            Map<Integer, CrossRankUnionWarWaitPatronData> patronsMap = waitPatronsMap.get(userId);
            for(CrossRankUnionWarWaitPatronData patronData : patronsMap.values()){
                if(patronData.getLine() != 0){
                    Map<Integer,CrossRankUnionWarWaitPatronData> patronsIndexMap = linePatronsMap.get(patronData.getLine());
                    if(patronData.getLineIndex() == 0){
                        logger.info("巅峰{}出现了门客派遣了却没有排序的userId:{},patronsId:{}",getActivityId(),patronData.getUserId(),patronData.getPatronId());
                    }else{
                        patronData.setLineIndex(patronsIndexMap.size() + 1);
                        addNeedUpdateWaitPatrons(patronData);
                    }
                    patronsIndexMap.put(patronData.getLineIndex(),patronData);
                }else{
                    if(!StringUtils.isNullOrEmpty(getUnionId(userId)) && getUnionId(userId).equals(battleMatch.getUnionId1())){
                        needAutoSendUnion1Patrons.add(patronData);
                    }else if(!StringUtils.isNullOrEmpty(getUnionId(userId)) && getUnionId(userId).equals(battleMatch.getUnionId2())){
                        needAutoSendUnion2Patrons.add(patronData);
                    }
                }
            }
        }
        logger.info("巅峰活动{}比赛进入进行中gameNo{}的比赛商会1有{}个门客没有上阵自动派遣",getActivityId(),battleMatch.getGameNo(),needAutoSendUnion1Patrons.size());
        logger.info("巅峰活动{}比赛进入进行中gameNo{}的比赛商会2有{}个门客没有上阵自动派遣",getActivityId(),battleMatch.getGameNo(),needAutoSendUnion2Patrons.size());
        int i = 1;
        //先归类,没有派遣的随机平局分配到五条线上
        while (needAutoSendUnion1Patrons.size() > 0){
            int line = i%6;
            int randomPatronsIndex = randomHelper.next(0,needAutoSendUnion1Patrons.size());
            CrossRankUnionWarWaitPatronData patronData = needAutoSendUnion1Patrons.get(randomPatronsIndex);
            patronData.setLine(line);
            //开战前没有分配的最后进入战斗要分配,排在最后面出战
//            patronData.setLineIndex(Integer.MAX_VALUE);
            patronData.setLineIndex(linePatronsMap.get(line).size() + 1);
            addNeedUpdateWaitPatrons(patronData);
            linePatronsMap.get(line).put(patronData.getLineIndex(),patronData);
            i++;
            if(i%6 == 0)i++;
            needAutoSendUnion1Patrons.remove(randomPatronsIndex);
        }
        i = 1;
        //先归类,没有派遣的随机平局分配到五条线上
        while (needAutoSendUnion2Patrons.size() > 0){
            int line = i%6;
            int randomPatronsIndex = randomHelper.next(0,needAutoSendUnion2Patrons.size());
            CrossRankUnionWarWaitPatronData patronData = needAutoSendUnion2Patrons.get(randomPatronsIndex);
            patronData.setLine(line);
            //开战前没有分配的最后进入战斗要分配,排在最后面出战
//            patronData.setLineIndex(Integer.MAX_VALUE);
            patronData.setLineIndex(linePatronsMap.get(line).size() + 1);
            addNeedUpdateWaitPatrons(patronData);
            linePatronsMap.get(line).put(patronData.getLineIndex(),patronData);
            i++;
            if(i%6 == 0)i++;
            needAutoSendUnion2Patrons.remove(randomPatronsIndex);
        }
        //开始战斗了，排一下序号
        sortLineSendPatrons(battleMatch);

        if(battleMatch.getMorale1() > battleMatch.getMorale2() || StringUtils.isNullOrEmpty(battleMatch.getUnionId2())){
            battleMatch.setAttackUnionId(battleMatch.getUnionId1());
        }else if(battleMatch.getMorale1() < battleMatch.getMorale2()){
            battleMatch.setAttackUnionId(battleMatch.getUnionId2());
        }else{
            CrossRankUnionWarUnionData unionData1 = getUnionData(battleMatch.getUnionId1());
            CrossRankUnionWarUnionData unionData2 = getUnionData(battleMatch.getUnionId2());
            if(unionData1.getUnionBaseInfo().getTotalEarnSpeed().compareTo(unionData2.getUnionBaseInfo().getTotalEarnSpeed()) >= 0){
                battleMatch.setAttackUnionId(battleMatch.getUnionId1());
            }else{
                battleMatch.setAttackUnionId(battleMatch.getUnionId2());
            }
        }

        buffWaitPatronsList(battleMatch);

        //归类玩开始分配
        for(int line : linePatronsMap.keySet()){
            CrossRankUnionWarLineData lineData = battleLineMap.get(line);
            Map<Integer,CrossRankUnionWarWaitPatronData> patronIndexMap = linePatronsMap.get(line);
            for(int lineIndex = 1;lineIndex <= patronIndexMap.size() ;lineIndex++){
                if(!patronIndexMap.containsKey(lineIndex)){
                    logger.error("巅峰{}出现门客序排序断层的情况gameNo:{},line:{},没有序号{}的门客",getActivityId(),battleMatch.getGameNo(),line,lineIndex);
                    continue;
                }
                CrossRankUnionWarWaitPatronData patronData = patronIndexMap.get(lineIndex);
                addPatronsToBattleLineVersion2(lineData,patronData,0,false);
            }
        }


        //把会长副会长搞成指导员,有得打才设置
        CrossRankUnionWarUnionData unionData = getUnionData(battleMatch.getUnionId1());
        Map<Integer, Map<Integer, List<Long>>> opMap = unionData.getOpUserIdMap();
        Map<Integer, List<Long>> lineMap = opMap.get(battleMatch.getGameNo());
        for(CrossRankUnionWarMemberData memberData : unionData.getMemberMap().values()){
            if(memberData.getPosition() == eUnionPosition.Master.getValue() || memberData.getPosition() == eUnionPosition.DeputyMaster.getValue()){
                for(int line = 1; line <= 5;line++){
                    List<Long> userIdlIst = lineMap.get(line);
                    if(!userIdlIst.contains(memberData.getUserId())){
                        userIdlIst.add(memberData.getUserId());
                    }
                }
            }
        }
        unionData.setOpUserIdMap(opMap);
        if(!StringUtils.isNullOrEmpty(battleMatch.getUnionId2())){
            CrossRankUnionWarUnionData union2Data = getUnionData(battleMatch.getUnionId2());
            Map<Integer, Map<Integer, List<Long>>> op2Map = union2Data.getOpUserIdMap();
            Map<Integer, List<Long>> line2Map = op2Map.get(battleMatch.getGameNo());
            for(CrossRankUnionWarMemberData memberData : union2Data.getMemberMap().values()){
                if(memberData.getPosition() == eUnionPosition.Master.getValue() || memberData.getPosition() == eUnionPosition.DeputyMaster.getValue()){
                    for(int line = 1; line <= 5;line++){
                        List<Long> userIdlIst = line2Map.get(line);
                        if(!userIdlIst.contains(memberData.getUserId())){
                            userIdlIst.add(memberData.getUserId());
                        }
                    }
                }
            }
            union2Data.setOpUserIdMap(op2Map);
        }
//        setLineWaitTime(battleMatch);
        RankUnionWarTimeConfig timeConfig = config.getTimeConfig(battleMatch.getTurn());
        long startBattleTime = timeConfig.getStartBattleTime();
        battleMatch.setBattleTime(startBattleTime);
        battleMatch.setStatus(1);
        addNeedUpdateMatch(battleMatch);
    }



    //门客没有派遣满的，自动给派遣
    private Map<Long,List<Integer>> getNeedUpWaitPatronMap(Map<Long, Map<Integer, CrossRankUnionWarWaitPatronData>> waitPatronsMap){
        int battleOccCount = config.getBattleOccCount();
        Map<Long,List<Integer>> retMap = new ConcurrentHashMap<>();
        //已经上了的列表
        Map<Long,Map<Integer,List<Integer>>> upMap = new ConcurrentHashMap<>();
        //还没上的列表
        Map<Long,Map<Integer,List<CrossRankUnionWarWaitPatronData>>> noUpMap = new ConcurrentHashMap<>();
        //分类一下玩家的门客，把不能上场的剔除掉
        for(long userId : waitPatronsMap.keySet()){
            retMap.put(userId,new ArrayList<>());
            Map<Integer,List<Integer>> upOccMap = new ConcurrentHashMap<>();
            for(eOccupationType occType : eOccupationType.values()){
                upOccMap.put((int)occType.getValue(),new ArrayList<>());
            }
            upMap.put(userId,upOccMap);
            noUpMap.put(userId,new ConcurrentHashMap<>());
            for(CrossRankUnionWarWaitPatronData waitPatronData : waitPatronsMap.get(userId).values()){
                PatronsInfo patronsInfo = PatronsMgr.getPatronsInfo(waitPatronData.getPatronId());
                if(waitPatronData.getLine() != 0){
                    if(upMap.get(userId).containsKey(patronsInfo.getOccupation())){
                        upMap.get(userId).put(patronsInfo.getOccupation(),new ArrayList<>());
                    }
                    upMap.get(userId).get(patronsInfo.getOccupation()).add(waitPatronData.getPatronId());
                }else{
                    int waitBattleTurn = getPatronsWaitBattleTurn(waitPatronData.getUserId(),waitPatronData.getPatronId());
                    if(waitBattleTurn == 0){
                        if(!noUpMap.get(userId).containsKey(patronsInfo.getOccupation())){
                            noUpMap.get(userId).put(patronsInfo.getOccupation(),new ArrayList<>());
                        }
                        noUpMap.get(userId).get(patronsInfo.getOccupation()).add(waitPatronData);
                    }
                }
            }
        }
        //将分类好的玩家的门客列表中没有达到人生要求的派遣再自动补派上去
        for(long userId : upMap.keySet()){
            Map<Integer,List<Integer>> occUserIdMap = upMap.get(userId);
            for(Integer occId : occUserIdMap.keySet()){
                if(occUserIdMap.get(occId).size() > battleOccCount){
                    logger.error("巅峰活动{}玩家{}上的职业{}门客大于配置{}个了，上了{}个",
                            getActivityId(),userId,occId,battleOccCount,occUserIdMap.get(occId).size());
                }
                if(occUserIdMap.get(occId).size() < battleOccCount){
                    int needAdd = battleOccCount - occUserIdMap.get(occId).size();
                    if(noUpMap.get(userId).containsKey(occId)){
                        List<CrossRankUnionWarWaitPatronData> patronsList = noUpMap.get(userId).get(occId);
                        patronsList.sort(new WaitPatronEarnSpeedSort());
                        while (needAdd > 0 && patronsList.size() > 0){
                            occUserIdMap.get(occId).add(patronsList.get(0).getPatronId());
                            retMap.get(userId).add(patronsList.get(0).getPatronId());
                            patronsList.remove(patronsList.get(0));
                            needAdd--;
                        }
                    }
                }
            }
        }
        return retMap;
    }

    //移除没有上阵的门客信息
    private void removeUnUpWaitPatrons(Map<Long, Map<Integer, CrossRankUnionWarWaitPatronData>> waitPatronsMap){
        //移除掉没有上阵的门客的
        for(Map<Integer,CrossRankUnionWarWaitPatronData> userWaitMap : waitPatronsMap.values()){
            List<CrossRankUnionWarWaitPatronData> tempMap = new ArrayList<>(userWaitMap.values());
            for(CrossRankUnionWarWaitPatronData waitPatronData : tempMap){
                if(waitPatronData.getLine() == 0){
                    userWaitMap.remove(waitPatronData.getPatronId());
                    addNeedDelWaitPatrons(waitPatronData);
                }else{
                    CrossRankUnionWarMemberData memberData = getUnionMember(waitPatronData.getUserId());
                    if(memberData != null){
                        int upTurn = getPatronsWaitBattleTurn(waitPatronData.getUserId(),waitPatronData.getPatronId());
                        if(upTurn != 0){
                            logger.info("巅峰活动{},不能上的门客被上了userId{},patronId{};",getActivityId(),waitPatronData.getUserId(),waitPatronData.getPatronId());
                        }
                        memberData.getPatronBattleTurnMap().put(waitPatronData.getPatronId(),crossRankUnionWarData.getGameTurn());
                    }
                }
            }
        }
    }

    /**
     * 进入战斗状态策划改版3
     * @param battleMatch
     */
    private void battleStatueGoingVersion3(CrossRankUnionWarMatchData battleMatch){
        logger.error("巅峰{}比赛gameNo:{}进入进行状态",getActivityId(),battleMatch.getGameNo());
        //没有派遣的自动给他派遣的列表;
        Map<Integer,Map<Integer,CrossRankUnionWarWaitPatronData>> linePatronsMap = new ConcurrentHashMap<>();
        for(int line = 1;line <= 5;line++){
            linePatronsMap.put(line,new ConcurrentHashMap<>());
        }
        Map<Integer, CrossRankUnionWarLineData> battleLineMap = battleMatch.getBattleLineMap();
        List<CrossRankUnionWarWaitPatronData> needAutoSendUnion1Patrons = new ArrayList<>();
        List<CrossRankUnionWarWaitPatronData> needAutoSendUnion2Patrons = new ArrayList<>();
        Map<Long, Map<Integer, CrossRankUnionWarWaitPatronData>> waitPatronsMap = new ConcurrentHashMap<>(battleMatch.getWaitPatronsMap());
        Map<Long,List<Integer>> needAddMap = getNeedUpWaitPatronMap(waitPatronsMap);
        for(long userId : needAddMap.keySet()){
            CrossRankUnionWarUnionData unionData = getUnionData(userId);
            if(unionData == null){
                logger.error("巅峰活动{},出现自动派遣时候找不到玩家{}的商会",getActivityId(),userId);
                continue;
            }
            List<Integer> needAddPatronsIdList = needAddMap.get(userId);
            for(Integer patronsId : needAddPatronsIdList){
                if(battleMatch.getUnionId1().equals(unionData.getUnionId())){
                    needAutoSendUnion1Patrons.add(waitPatronsMap.get(userId).get(patronsId));
                }else if(battleMatch.getUnionId2().equals(unionData.getUnionId())){
                    needAutoSendUnion2Patrons.add(waitPatronsMap.get(userId).get(patronsId));
                }
            }
        }
        logger.info("巅峰活动{}比赛进入进行中gameNo{}的比赛商会1有{}个门客没有上阵自动派遣",getActivityId(),battleMatch.getGameNo(),needAutoSendUnion1Patrons.size());
        logger.info("巅峰活动{}比赛进入进行中gameNo{}的比赛商会2有{}个门客没有上阵自动派遣",getActivityId(),battleMatch.getGameNo(),needAutoSendUnion2Patrons.size());
        int i = 1;
        //先归类,没有派遣的随机平局分配到五条线上
        while (needAutoSendUnion1Patrons.size() > 0){
            int line = i%6;
            int randomPatronsIndex = randomHelper.next(0,needAutoSendUnion1Patrons.size());
            CrossRankUnionWarWaitPatronData patronData = needAutoSendUnion1Patrons.get(randomPatronsIndex);
            patronData.setLine(line);
            //开战前没有分配的最后进入战斗要分配,排在最后面出战
//            patronData.setLineIndex(Integer.MAX_VALUE);
            patronData.setLineIndex(linePatronsMap.get(line).size() + 1);
            addNeedUpdateWaitPatrons(patronData);
            linePatronsMap.get(line).put(patronData.getLineIndex(),patronData);
            i++;
            if(i%6 == 0)i++;
            needAutoSendUnion1Patrons.remove(randomPatronsIndex);
        }
        i = 1;
        //先归类,没有派遣的随机平局分配到五条线上
        while (needAutoSendUnion2Patrons.size() > 0){
            int line = i%6;
            int randomPatronsIndex = randomHelper.next(0,needAutoSendUnion2Patrons.size());
            CrossRankUnionWarWaitPatronData patronData = needAutoSendUnion2Patrons.get(randomPatronsIndex);
            patronData.setLine(line);
            //开战前没有分配的最后进入战斗要分配,排在最后面出战
//            patronData.setLineIndex(Integer.MAX_VALUE);
            patronData.setLineIndex(linePatronsMap.get(line).size() + 1);
            addNeedUpdateWaitPatrons(patronData);
            linePatronsMap.get(line).put(patronData.getLineIndex(),patronData);
            i++;
            if(i%6 == 0)i++;
            needAutoSendUnion2Patrons.remove(randomPatronsIndex);
        }
        //开始战斗了，排一下序号
        sortLineSendPatrons(battleMatch);

        removeUnUpWaitPatrons(waitPatronsMap);

        if(battleMatch.getMorale1() > battleMatch.getMorale2() || StringUtils.isNullOrEmpty(battleMatch.getUnionId2())){
            battleMatch.setAttackUnionId(battleMatch.getUnionId1());
        }else if(battleMatch.getMorale1() < battleMatch.getMorale2()){
            battleMatch.setAttackUnionId(battleMatch.getUnionId2());
        }else{
            CrossRankUnionWarUnionData unionData1 = getUnionData(battleMatch.getUnionId1());
            CrossRankUnionWarUnionData unionData2 = getUnionData(battleMatch.getUnionId2());
            if(unionData1.getUnionBaseInfo().getTotalEarnSpeed().compareTo(unionData2.getUnionBaseInfo().getTotalEarnSpeed()) >= 0){
                battleMatch.setAttackUnionId(battleMatch.getUnionId1());
            }else{
                battleMatch.setAttackUnionId(battleMatch.getUnionId2());
            }
        }

        buffWaitPatronsList(battleMatch);

        //归类玩开始分配
        for(int line : linePatronsMap.keySet()){
            CrossRankUnionWarLineData lineData = battleLineMap.get(line);
            Map<Integer,CrossRankUnionWarWaitPatronData> patronIndexMap = linePatronsMap.get(line);
            for(int lineIndex = 1;lineIndex <= patronIndexMap.size() ;lineIndex++){
                if(!patronIndexMap.containsKey(lineIndex)){
                    logger.error("巅峰{}出现门客序排序断层的情况gameNo:{},line:{},没有序号{}的门客",getActivityId(),battleMatch.getGameNo(),line,lineIndex);
                    continue;
                }
                CrossRankUnionWarWaitPatronData patronData = patronIndexMap.get(lineIndex);
                addPatronsToBattleLineVersion2(lineData,patronData,0,false);
            }
        }


        //把会长副会长搞成指导员,有得打才设置
        CrossRankUnionWarUnionData unionData = getUnionData(battleMatch.getUnionId1());
        Map<Integer, Map<Integer, List<Long>>> opMap = unionData.getOpUserIdMap();
        Map<Integer, List<Long>> lineMap = opMap.get(battleMatch.getGameNo());
        for(CrossRankUnionWarMemberData memberData : unionData.getMemberMap().values()){
            if(memberData.getPosition() == eUnionPosition.Master.getValue() || memberData.getPosition() == eUnionPosition.DeputyMaster.getValue()){
                for(int line = 1; line <= 5;line++){
                    List<Long> userIdlIst = lineMap.get(line);
                    if(!userIdlIst.contains(memberData.getUserId())){
                        userIdlIst.add(memberData.getUserId());
                    }
                }
            }
        }
        unionData.setOpUserIdMap(opMap);
        if(!StringUtils.isNullOrEmpty(battleMatch.getUnionId2())){
            CrossRankUnionWarUnionData union2Data = getUnionData(battleMatch.getUnionId2());
            Map<Integer, Map<Integer, List<Long>>> op2Map = union2Data.getOpUserIdMap();
            Map<Integer, List<Long>> line2Map = op2Map.get(battleMatch.getGameNo());
            for(CrossRankUnionWarMemberData memberData : union2Data.getMemberMap().values()){
                if(memberData.getPosition() == eUnionPosition.Master.getValue() || memberData.getPosition() == eUnionPosition.DeputyMaster.getValue()){
                    for(int line = 1; line <= 5;line++){
                        List<Long> userIdlIst = line2Map.get(line);
                        if(!userIdlIst.contains(memberData.getUserId())){
                            userIdlIst.add(memberData.getUserId());
                        }
                    }
                }
            }
            union2Data.setOpUserIdMap(op2Map);
        }
//        setLineWaitTime(battleMatch);
        RankUnionWarTimeConfig timeConfig = config.getTimeConfig(battleMatch.getTurn());
        long startBattleTime = timeConfig.getStartBattleTime();
        battleMatch.setBattleTime(startBattleTime);
        battleMatch.setStatus(1);
        addNeedUpdateMatch(battleMatch);
    }

    //全部去线路1，测试一个bug
    private void battleStatueGoingVersionDebug(CrossRankUnionWarMatchData battleMatch){
        logger.error("巅峰{}比赛gameNo:{}进入进行状态",getActivityId(),battleMatch.getGameNo());
        //没有派遣的自动给他派遣的列表;
        Map<Integer,Map<String,Map<Integer,CrossRankUnionWarWaitPatronData>>> linePatronsMap = new ConcurrentHashMap<>();
        for(int line = 1;line <= 5;line++){
            Map<String,Map<Integer,CrossRankUnionWarWaitPatronData>> unionPatronMap = new ConcurrentHashMap<>();
            unionPatronMap.put(battleMatch.getUnionId1(),new ConcurrentHashMap<>());
            unionPatronMap.put(battleMatch.getUnionId2(),new ConcurrentHashMap<>());
            linePatronsMap.put(line,unionPatronMap);
        }
        Map<Integer, CrossRankUnionWarLineData> battleLineMap = battleMatch.getBattleLineMap();
        List<CrossRankUnionWarWaitPatronData> needAutoSendUnion1Patrons = new ArrayList<>();
        List<CrossRankUnionWarWaitPatronData> needAutoSendUnion2Patrons = new ArrayList<>();
        Map<Long, Map<Integer, CrossRankUnionWarWaitPatronData>> waitPatronsMap = new ConcurrentHashMap<>(battleMatch.getWaitPatronsMap());
        for(long userId : waitPatronsMap.keySet()){
            Map<Integer, CrossRankUnionWarWaitPatronData> patronsMap = waitPatronsMap.get(userId);
            for(CrossRankUnionWarWaitPatronData waitPatronData : patronsMap.values()){
                if(waitPatronData.getLine() != 0){
                    CrossRankUnionWarUnionData unionData = getUnionData(waitPatronData.getUserId());
                    if(unionData == null)continue;
                    Map<Integer,CrossRankUnionWarWaitPatronData> patronsIndexMap = linePatronsMap.get(waitPatronData.getLine()).get(unionData.getUnionId());
                    if(waitPatronData.getLineIndex() == 0){
                        logger.info("巅峰{}出现了门客派遣了却没有排序的userId:{},patronsId:{}",getActivityId(),waitPatronData.getUserId(),waitPatronData.getPatronId());
                    }
                    patronsIndexMap.put(waitPatronData.getLineIndex(),waitPatronData);
                }
            }
        }
        Map<Long,List<Integer>> needAddMap = getNeedUpWaitPatronMap(waitPatronsMap);
        for(long userId : needAddMap.keySet()){
            CrossRankUnionWarUnionData unionData = getUnionData(userId);
            if(unionData == null){
                logger.info("巅峰活动{},出现自动派遣时候找不到玩家{}的商会",getActivityId(),userId);
                continue;
            }
            List<Integer> needAddPatronsIdList = needAddMap.get(userId);
            for(Integer patronsId : needAddPatronsIdList){
                if(battleMatch.getUnionId1().equals(unionData.getUnionId())){
                    needAutoSendUnion1Patrons.add(waitPatronsMap.get(userId).get(patronsId));
                }else if(battleMatch.getUnionId2().equals(unionData.getUnionId())){
                    needAutoSendUnion2Patrons.add(waitPatronsMap.get(userId).get(patronsId));
                }
            }
        }
        logger.info("巅峰活动{}比赛进入进行中gameNo{}的比赛商会1有{}个门客没有上阵自动派遣",getActivityId(),battleMatch.getGameNo(),needAutoSendUnion1Patrons.size());
        logger.info("巅峰活动{}比赛进入进行中gameNo{}的比赛商会2有{}个门客没有上阵自动派遣",getActivityId(),battleMatch.getGameNo(),needAutoSendUnion2Patrons.size());
        int i = 1;
        //先归类,没有派遣的随机平局分配到五条线上
        while (needAutoSendUnion1Patrons.size() > 0){
            int line = i%6;
            int randomPatronsIndex = randomHelper.next(0,needAutoSendUnion1Patrons.size());
            CrossRankUnionWarWaitPatronData patronData = needAutoSendUnion1Patrons.get(randomPatronsIndex);
            patronData.setLine(line);
            //开战前没有分配的最后进入战斗要分配,排在最后面出战
//            patronData.setLineIndex(Integer.MAX_VALUE);
            patronData.setLineIndex(linePatronsMap.get(line).get(battleMatch.getUnionId1()).size() + 1);
            addNeedUpdateWaitPatrons(patronData);
            linePatronsMap.get(line).get(battleMatch.getUnionId1()).put(patronData.getLineIndex(),patronData);
            i++;
            if(i%6 == 0)i++;
            needAutoSendUnion1Patrons.remove(randomPatronsIndex);
        }
        i = 1;
        //先归类,没有派遣的随机平局分配到五条线上
        while (needAutoSendUnion2Patrons.size() > 0){
            int line = i%6;
            int randomPatronsIndex = randomHelper.next(0,needAutoSendUnion2Patrons.size());
            CrossRankUnionWarWaitPatronData patronData = needAutoSendUnion2Patrons.get(randomPatronsIndex);
            patronData.setLine(line);
            //开战前没有分配的最后进入战斗要分配,排在最后面出战
//            patronData.setLineIndex(Integer.MAX_VALUE);
            patronData.setLineIndex(linePatronsMap.get(line).get(battleMatch.getUnionId2()).size() + 1);
            addNeedUpdateWaitPatrons(patronData);
            linePatronsMap.get(line).get(battleMatch.getUnionId2()).put(patronData.getLineIndex(),patronData);
            i++;
            if(i%6 == 0)i++;
            needAutoSendUnion2Patrons.remove(randomPatronsIndex);
        }
        //开始战斗了，排一下序号
        sortLineSendPatrons(battleMatch);

        removeUnUpWaitPatrons(waitPatronsMap);

        if(battleMatch.getMorale1() > battleMatch.getMorale2() || StringUtils.isNullOrEmpty(battleMatch.getUnionId2())){
            battleMatch.setAttackUnionId(battleMatch.getUnionId1());
        }else if(battleMatch.getMorale1() < battleMatch.getMorale2()){
            battleMatch.setAttackUnionId(battleMatch.getUnionId2());
        }else{
            CrossRankUnionWarUnionData unionData1 = getUnionData(battleMatch.getUnionId1());
            CrossRankUnionWarUnionData unionData2 = getUnionData(battleMatch.getUnionId2());
            if(unionData1.getUnionBaseInfo().getTotalEarnSpeed().compareTo(unionData2.getUnionBaseInfo().getTotalEarnSpeed()) >= 0){
                battleMatch.setAttackUnionId(battleMatch.getUnionId1());
            }else{
                battleMatch.setAttackUnionId(battleMatch.getUnionId2());
            }
        }

        buffWaitPatronsList(battleMatch);

        //归类玩开始分配
        for(int line : linePatronsMap.keySet()){
            CrossRankUnionWarLineData lineData = battleLineMap.get(line);
            Map<String,Map<Integer,CrossRankUnionWarWaitPatronData>> unionPatronIndexMap = linePatronsMap.get(line);
            for(Map<Integer,CrossRankUnionWarWaitPatronData> patronIndexMap : unionPatronIndexMap.values()){
                for(int lineIndex = 1;lineIndex <= patronIndexMap.size() ;lineIndex++){
                    if(!patronIndexMap.containsKey(lineIndex)){
                        logger.error("巅峰{}出现门客序排序断层的情况gameNo:{},line:{},没有序号{}的门客",getActivityId(),battleMatch.getGameNo(),line,lineIndex);
                        continue;
                    }
                    CrossRankUnionWarWaitPatronData patronData = patronIndexMap.get(lineIndex);
                    addPatronsToBattleLineVersion2(lineData,patronData,0,false);
                }
            }
        }


        //把会长副会长搞成指导员,有得打才设置
        CrossRankUnionWarUnionData unionData = getUnionData(battleMatch.getUnionId1());
        Map<Integer, Map<Integer, List<Long>>> opMap = unionData.getOpUserIdMap();
        Map<Integer, List<Long>> lineMap = opMap.get(battleMatch.getGameNo());
        for(CrossRankUnionWarMemberData memberData : unionData.getMemberMap().values()){
            if(memberData.getPosition() == eUnionPosition.Master.getValue() || memberData.getPosition() == eUnionPosition.DeputyMaster.getValue()){
                for(int line = 1; line <= 5;line++){
                    List<Long> userIdlIst = lineMap.get(line);
                    if(!userIdlIst.contains(memberData.getUserId())){
                        userIdlIst.add(memberData.getUserId());
                    }
                }
            }
        }
        unionData.setOpUserIdMap(opMap);
        if(!StringUtils.isNullOrEmpty(battleMatch.getUnionId2())){
            CrossRankUnionWarUnionData union2Data = getUnionData(battleMatch.getUnionId2());
            Map<Integer, Map<Integer, List<Long>>> op2Map = union2Data.getOpUserIdMap();
            Map<Integer, List<Long>> line2Map = op2Map.get(battleMatch.getGameNo());
            for(CrossRankUnionWarMemberData memberData : union2Data.getMemberMap().values()){
                if(memberData.getPosition() == eUnionPosition.Master.getValue() || memberData.getPosition() == eUnionPosition.DeputyMaster.getValue()){
                    for(int line = 1; line <= 5;line++){
                        List<Long> userIdlIst = line2Map.get(line);
                        if(!userIdlIst.contains(memberData.getUserId())){
                            userIdlIst.add(memberData.getUserId());
                        }
                    }
                }
            }
            union2Data.setOpUserIdMap(op2Map);
        }
//        setLineWaitTime(battleMatch);
        RankUnionWarTimeConfig timeConfig = config.getTimeConfig(battleMatch.getTurn());
        long startBattleTime = timeConfig.getStartBattleTime();
        battleMatch.setBattleTime(startBattleTime);
        battleMatch.setStatus(1);
        addNeedUpdateMatch(battleMatch);
    }

    /**
     * 进入战斗状态策划又双改版4
     * @param battleMatch
     */
    private void battleStatueGoingVersion4(CrossRankUnionWarMatchData battleMatch){
        logger.error("巅峰{}比赛gameNo:{}进入进行状态",getActivityId(),battleMatch.getGameNo());
        //没有派遣的自动给他派遣的列表;
        Map<Integer,Map<String,Map<Integer,CrossRankUnionWarWaitPatronData>>> linePatronsMap = new ConcurrentHashMap<>();
        for(int line = 1;line <= 5;line++){
            Map<String,Map<Integer,CrossRankUnionWarWaitPatronData>> unionPatronMap = new ConcurrentHashMap<>();
            unionPatronMap.put(battleMatch.getUnionId1(),new ConcurrentHashMap<>());
            unionPatronMap.put(battleMatch.getUnionId2(),new ConcurrentHashMap<>());
            linePatronsMap.put(line,unionPatronMap);
        }
        Map<Integer, CrossRankUnionWarLineData> battleLineMap = battleMatch.getBattleLineMap();
        Map<Long, Map<Integer, CrossRankUnionWarWaitPatronData>> waitPatronsMap = new ConcurrentHashMap<>(battleMatch.getWaitPatronsMap());
        for(long userId : waitPatronsMap.keySet()){
            Map<Integer, CrossRankUnionWarWaitPatronData> patronsMap = waitPatronsMap.get(userId);
            for(CrossRankUnionWarWaitPatronData waitPatronData : patronsMap.values()){
                if(waitPatronData.getLine() != 0){
                    CrossRankUnionWarUnionData unionData = getUnionData(waitPatronData.getUserId());
                    if(unionData == null)continue;
                    Map<Integer,CrossRankUnionWarWaitPatronData> patronsIndexMap = linePatronsMap.get(waitPatronData.getLine()).get(unionData.getUnionId());
                    if(waitPatronData.getLineIndex() == 0){
                        logger.info("巅峰{}出现了门客派遣了却没有排序的userId:{},patronsId:{}",getActivityId(),waitPatronData.getUserId(),waitPatronData.getPatronId());
                    }
                    patronsIndexMap.put(waitPatronData.getLineIndex(),waitPatronData);
                }
            }
        }
        //开始战斗了，排一下序号
        sortLineSendPatrons(battleMatch);
        removeUnUpWaitPatrons(waitPatronsMap);
        if(battleMatch.getMorale1() > battleMatch.getMorale2() || StringUtils.isNullOrEmpty(battleMatch.getUnionId2())){
            battleMatch.setAttackUnionId(battleMatch.getUnionId1());
        }else if(battleMatch.getMorale1() < battleMatch.getMorale2()){
            battleMatch.setAttackUnionId(battleMatch.getUnionId2());
        }else{
            CrossRankUnionWarUnionData unionData1 = getUnionData(battleMatch.getUnionId1());
            CrossRankUnionWarUnionData unionData2 = getUnionData(battleMatch.getUnionId2());
            if(unionData1.getUnionBaseInfo().getTotalEarnSpeed().compareTo(unionData2.getUnionBaseInfo().getTotalEarnSpeed()) >= 0){
                battleMatch.setAttackUnionId(battleMatch.getUnionId1());
            }else{
                battleMatch.setAttackUnionId(battleMatch.getUnionId2());
            }
        }

        buffWaitPatronsList(battleMatch);

        buffPatronsSkill(battleMatch);

        //归类玩开始分配
        for(int line : linePatronsMap.keySet()){
            CrossRankUnionWarLineData lineData = battleLineMap.get(line);
            Map<String,Map<Integer,CrossRankUnionWarWaitPatronData>> unionPatronIndexMap = linePatronsMap.get(line);
            for(Map<Integer,CrossRankUnionWarWaitPatronData> patronIndexMap : unionPatronIndexMap.values()){
                for(int lineIndex = 1;lineIndex <= patronIndexMap.size() ;lineIndex++){
                    if(!patronIndexMap.containsKey(lineIndex)){
                        logger.error("巅峰{}出现门客序排序断层的情况gameNo:{},line:{},没有序号{}的门客",getActivityId(),battleMatch.getGameNo(),line,lineIndex);
                        continue;
                    }
                    CrossRankUnionWarWaitPatronData patronData = patronIndexMap.get(lineIndex);
                    addPatronsToBattleLineVersion2(lineData,patronData,0,false);
                }
            }
        }

        //把会长副会长搞成指导员,有得打才设置
        CrossRankUnionWarUnionData unionData = getUnionData(battleMatch.getUnionId1());
        Map<Integer, Map<Integer, List<Long>>> opMap = unionData.getOpUserIdMap();
        Map<Integer, List<Long>> lineMap = opMap.get(battleMatch.getGameNo());
        for(CrossRankUnionWarMemberData memberData : unionData.getMemberMap().values()){
            if(memberData.getPosition() == eUnionPosition.Master.getValue() || memberData.getPosition() == eUnionPosition.DeputyMaster.getValue()){
                for(int line = 1; line <= 5;line++){
                    List<Long> userIdlIst = lineMap.get(line);
                    if(!userIdlIst.contains(memberData.getUserId())){
                        userIdlIst.add(memberData.getUserId());
                    }
                }
            }
        }
        unionData.setOpUserIdMap(opMap);
        if(!StringUtils.isNullOrEmpty(battleMatch.getUnionId2())){
            CrossRankUnionWarUnionData union2Data = getUnionData(battleMatch.getUnionId2());
            Map<Integer, Map<Integer, List<Long>>> op2Map = union2Data.getOpUserIdMap();
            Map<Integer, List<Long>> line2Map = op2Map.get(battleMatch.getGameNo());
            for(CrossRankUnionWarMemberData memberData : union2Data.getMemberMap().values()){
                if(memberData.getPosition() == eUnionPosition.Master.getValue() || memberData.getPosition() == eUnionPosition.DeputyMaster.getValue()){
                    for(int line = 1; line <= 5;line++){
                        List<Long> userIdlIst = line2Map.get(line);
                        if(!userIdlIst.contains(memberData.getUserId())){
                            userIdlIst.add(memberData.getUserId());
                        }
                    }
                }
            }
            union2Data.setOpUserIdMap(op2Map);
        }
//        setLineWaitTime(battleMatch);
        RankUnionWarTimeConfig timeConfig = config.getTimeConfig(battleMatch.getTurn());
        long startBattleTime = timeConfig.getStartBattleTime();
        battleMatch.setBattleTime(startBattleTime);
        battleMatch.setStatus(1);
        addNeedUpdateMatch(battleMatch);
    }

    /**
     * 士气比拼完之后加上赚速buff
     * @param battleMatch
     */
    private void buffWaitPatronsList(CrossRankUnionWarMatchData battleMatch){
        if(StringUtils.isNullOrEmpty(battleMatch.getAttackUnionId())){
            return;
        }
        Map<Long, Map<Integer, CrossRankUnionWarWaitPatronData>> userWaitPatronMap = new ConcurrentHashMap<>(battleMatch.getWaitPatronsMap());
        CrossRankUnionWarUnionData unionData = getUnionData(battleMatch.getAttackUnionId());
        for(CrossRankUnionWarMemberData memberData : unionData.getMemberMap().values()){
            if(userWaitPatronMap.containsKey(memberData.getUserId())){
                for(CrossRankUnionWarWaitPatronData waitPatronData : userWaitPatronMap.get(memberData.getUserId()).values()){
                    BigInteger buffEarnSpeed = waitPatronData.getEarnSpeed().multiply(BigInteger.valueOf(config.getGuwuAdd() + 1000)).divide(BigInteger.valueOf(1000));
                    waitPatronData.setEarnSpeed(buffEarnSpeed);
                    addNeedUpdateWaitPatrons(waitPatronData);
                }
            }
        }
    }

    //新加的李刚技能加出战门客赚速
    private void buffPatronsSkill(CrossRankUnionWarMatchData battleMatch){
        Map<Long, Map<Integer, CrossRankUnionWarWaitPatronData>> userWaitPatronMap = new ConcurrentHashMap<>(battleMatch.getWaitPatronsMap());
        for(Map<Integer, CrossRankUnionWarWaitPatronData> waitPatronDataMap : userWaitPatronMap.values()){
            for(CrossRankUnionWarWaitPatronData waitPatronData : waitPatronDataMap.values()){
                CrossRankUnionWarMemberData unionWarMemberData = getUnionMember(waitPatronData.getUserId());
                if(unionWarMemberData != null && unionWarMemberData.getPatronsSkillAdd() > 0){
                    BigInteger buffEarnSpeed = waitPatronData.getEarnSpeed().multiply(BigInteger.valueOf(unionWarMemberData.getPatronsSkillAdd() + 1000)).divide(BigInteger.valueOf(1000));
                    waitPatronData.setEarnSpeed(buffEarnSpeed);
                    addNeedUpdateWaitPatrons(waitPatronData);
                }
            }
        }
    }

    /**
     * 设置一下等待时间，不然进去太快时间还没有来得及设置，如果没有门客开打
     * 原本战斗一开始就比赛了，可以吧对面没人的设置上等待时间，现在不行了
     * @param battleMatch
     */
    private void setLineWaitTime(CrossRankUnionWarMatchData battleMatch){
        RankUnionWarTimeConfig timeConfig = config.getTimeConfig(battleMatch.getTurn());
        if(StringUtils.isNullOrEmpty(battleMatch.getUnionId2())){
            for(CrossRankUnionWarLineData lineData : battleMatch.getBattleLineMap().values()){
                if(lineData.getBattlePatronsMap().get(battleMatch.getUnionId1()).size() > 0){
                    lineData.setUnion2StartWaitTime(timeConfig.getStartBattleTime());
                }
                addNeedUpdateLine(lineData);
            }
        }else{
            for(CrossRankUnionWarLineData lineData : battleMatch.getBattleLineMap().values()){
                int union1PatronSize = lineData.getBattlePatronsMap().get(battleMatch.getUnionId1()).size();
                int union2PatronSize = lineData.getBattlePatronsMap().get(battleMatch.getUnionId2()).size();
                if(union1PatronSize == 0 && union2PatronSize > 0){
                    lineData.setUnion1StartWaitTime(timeConfig.getStartBattleTime());
                }else if(union1PatronSize > 0 && union2PatronSize == 0){
                    lineData.setUnion2StartWaitTime(timeConfig.getStartBattleTime());
                }
                addNeedUpdateLine(lineData);
            }
        }
    }

    //上阵了就锁定门客的座驾和鱼
    private void patronsVehicleAndFishLock(CrossRankUnionWarWaitPatronData waitPatronsData){
        CrossRankUnionWarMatchData matchData = getIngGameNoMatch(waitPatronsData.getGameNo());
        if(matchData == null){
            logger.info("巅峰活动{},锁定门客{}坐骑和鱼失败没有找到进行中的比赛",getActivityId(),waitPatronsData.getPatronId());
            return;
        }
        CrossRankUnionWarPatronData patronData = getPatronsInfo(waitPatronsData);
        if(patronData == null){
            logger.info("巅峰活动{},锁定门客{}坐骑和鱼失败没有找到对应轮次{}的门客了",getActivityId(),waitPatronsData.getPatronId(),matchData.getTurn());
            return;
        }
        CrossRankUnionWarUserLockData userLockData = getUserVFLock(waitPatronsData.getUserId());
        if(userLockData == null){
            logger.info("巅峰活动{},找不到玩家{}的锁定数据",getActivityId(),waitPatronsData.getUserId());
            return;
        }
        Map<String, Integer> userVehiclePatronsMap = getUserVehiclePatronsMap(waitPatronsData.getUserId());
        Map<Integer, Integer> userFishPatronsMap = getUserFishPatronsMap(waitPatronsData.getUserId());
        Map<Integer, Integer> userCricketPatronsMap = getUserCricketPatronsMap(waitPatronsData.getUserId());
        if(!StringUtils.isNullOrEmpty(patronData.getVehicleUid())){
            if(!userVehiclePatronsMap.containsKey(patronData.getVehicleUid())){
                userVehiclePatronsMap.put(patronData.getVehicleUid(),patronData.getPatronsId());
            }else{
                if(userVehiclePatronsMap.get(patronData.getVehicleUid()) != patronData.getPatronsId()){
                    logger.info("巅峰活动{},珍兽已经被绑定了，绑定在{}上，还要绑定在{}上",
                            getActivityId(),userVehiclePatronsMap.get(patronData.getVehicleUid()),patronData.getPatronsId());
                }
            }
        }
        if(patronData.getFishId() != 0){
            if(!userFishPatronsMap.containsKey(patronData.getFishId())){
                userFishPatronsMap.put(patronData.getFishId(),patronData.getPatronsId());
            }else{
                logger.info("巅峰活动{},鱼已经被绑定了，绑定在{}上，还要绑定在{}上",
                        getActivityId(),userFishPatronsMap.get(patronData.getFishId()),patronData.getPatronsId());
            }
        }
        if(patronData.getCricketId() != 0){
            if(!userCricketPatronsMap.containsKey(patronData.getCricketId())){
                userCricketPatronsMap.put(patronData.getCricketId(),patronData.getPatronsId());
            }else{
                logger.info("巅峰活动{},虫已经被绑定了，绑定在{}上，还要绑定在{}上",
                        getActivityId(),userCricketPatronsMap.get(patronData.getCricketId()),patronData.getPatronsId());
            }
        }
//        logger.error("巅峰活动{},玩家{}的门客{}坐骑和鱼处理完锁定",getActivityId(),patronData.getUserId(),patronData.getPatronsId());
        addNeedUpdateUserLock(userLockData);
    }

    /**
     * 把一个门客正式加入到战斗队列
     * @param lineData
     * @param waitPatronsData
     * @param dieTime 复活前还没死，死亡时间就是复活时间，复活前已经死，复活操作时间就是复活时间
     * @param isGaming 是不是游戏中的派遣，是的话会一派遣就是战斗
     */
    private void addPatronsToBattleLineVersion2(CrossRankUnionWarLineData lineData,CrossRankUnionWarWaitPatronData waitPatronsData,long dieTime,boolean isGaming){
        waitPatronsData.setLine(lineData.getLine());
        Map<String, Map<Integer, CrossRankUnionWarBattlePatronData>> battleMap = lineData.getBattlePatronsMap();
        CrossRankUnionWarUnionData unionData = getUnionData(waitPatronsData.getUserId());
        if(unionData == null){
            return;
        }
        int lineIndex = 0;
        //全部都死光了派遣下来就是战斗时间
        if(unionData.getUnionId().equals(lineData.getUnionId1())){
            lineIndex = lineData.getLineIndex1AndIncrement();
        }else{
            lineIndex = lineData.getLineIndex2AndIncrement();
        }
        if(isGaming){
            if(unionData.getUnionId().equals(lineData.getUnionId1()) && lineData.getUnion1StartWaitTime() > 0){
                lineData.setUnion1WaitTime(lineData.getUnion1WaitTime() + dieTime - lineData.getUnion1StartWaitTime());
                lineData.setUnion1StartWaitTime(0);
            }
            if(unionData.getUnionId().equals(lineData.getUnionId2()) && lineData.getUnion2StartWaitTime() > 0){
                lineData.setUnion2WaitTime(lineData.getUnion2WaitTime() + dieTime - lineData.getUnion2StartWaitTime());
                lineData.setUnion2StartWaitTime(0);
            }
            //对面也没人
            if(unionData.getUnionId().equals(lineData.getUnionId1()) &&
                    getAlivePatron(lineData.getBattlePatronsMap().get(lineData.getUnionId2())) == null
                    && lineData.getUnion2StartWaitTime() == 0){
                lineData.setUnion2StartWaitTime(dieTime);
            }
            if(unionData.getUnionId().equals(lineData.getUnionId2()) &&
                    getAlivePatron(lineData.getBattlePatronsMap().get(lineData.getUnionId1())) == null
                && lineData.getUnion1StartWaitTime() == 0){
                lineData.setUnion1StartWaitTime(dieTime);
            }
        }
        CrossRankUnionWarBattlePatronData battlePatronData = initBattlePatrons(lineIndex,waitPatronsData,dieTime);
        battleMap.get(unionData.getUnionId()).put(lineIndex,battlePatronData);
        addNeedInsertBattlePatrons(battlePatronData);
        //默认一次出场，再次就是买活，用来复活
        waitPatronsData.setBattleTimes(waitPatronsData.getBattleTimes() + 1);
        lineData.setBattlePatronsMap(battleMap);
        addNeedUpdateWaitPatrons(waitPatronsData);
        addNeedUpdateLine(lineData);
        if(!isGaming){
            patronsVehicleAndFishLock(waitPatronsData);
        }
    }

    //生成下一轮的时候就清除上一轮数据
    private void clearBattle(int turn){
        if(turn > 0){
            Map<Integer, List<CrossRankUnionWarMatchData>> divisionMap = turnDivisionMatchMap.get(turn);
            for(List<CrossRankUnionWarMatchData> matchList : divisionMap.values()){
                for(CrossRankUnionWarMatchData battleMatch : matchList){
                    //比赛结束了清掉数据
                    clearBattleMatchData(battleMatch);
                }
            }
        }
    }

    //数据太大了，每一轮新的比赛开始就把旧的数据清掉
    private void clearWaitPatrons(int turn){
        RankUnionWarTimeConfig timeConfig = config.getLastTimeConfig();
        if(timeConfig.getSession() > turn){
            if(turn > 0){
                Map<String, CrossRankUnionWarUnionData> tempUnionDataMap = new ConcurrentHashMap<>(unionDataMap);
                for(CrossRankUnionWarUnionData unionData : tempUnionDataMap.values()){
                    Map<Long, CrossRankUnionWarMemberData> memberDataMap = new ConcurrentHashMap<>(unionData.getMemberMap());
                    //原本是每一轮都拉六个不一样的，策划又改成每一轮是全部了，直接上一轮的方法下一轮
                    for(CrossRankUnionWarMemberData memberData : memberDataMap.values()){
                        memberData.getPatronDataMap().put(turn + 1,memberData.getPatronDataMap().get(turn));
                        memberData.getPatronDataMap().remove(turn);
                    }
                    unionData.setMemberMap(memberDataMap);
                }
            }
        }
    }

    public void clearLog(int turn){
        for(CrossRankUnionWarMatchData matchData : battleMatchMap.values()){
            if(turn == matchData.getTurn()){
                if(debugBattleMap.containsKey(matchData.getGameNo())){
                    debugBattleMap.get(matchData.getGameNo()).clear();
                }
            }
        }
    }

    /**
     * 进入结束画面
     * @param battleMatch
     */
    private void battleStatueOver(CrossRankUnionWarMatchData battleMatch){
        long nowTime = config.getTimeConfig(battleMatch.getTurn()).getEndTime();
        battlingMatchMap.remove(battleMatch.getGameNo());

        CrossRankUnionWarUnionData union1Data = getUnionData(battleMatch.getUnionId1());
        CrossRankUnionWarUnionData union2Data = getUnionData(battleMatch.getUnionId2());

        //当活动时间结束时，仍未分出胜负，则占点较多的商会获胜，若占点数量一致，则根据败敌数判断，败敌数较多的一方获胜，若败敌数也相同，则商会赚速较高的一方获得本场战斗的胜利
        if(StringUtils.isNullOrEmpty(battleMatch.getWinUnionId())){
            int union1WinCount = 0;
            int union2WinCount = 0;
            for(CrossRankUnionWarLineData lineData : battleMatch.getBattleLineMap().values()){
                //没有决出胜负的线路
                if(!StringUtils.isNullOrEmpty(lineData.getWinUnionId())){
                    if(lineData.getWinUnionId().equals(battleMatch.getUnionId1())){
                        union1WinCount++;
                    }else{
                        union2WinCount++;
                    }
                }
            }
            if(union1WinCount > union2WinCount){
                setWinUnion(battleMatch,battleMatch.getUnionId1(),nowTime);
            }else if(union1WinCount < union2WinCount){
                setWinUnion(battleMatch,battleMatch.getUnionId2(),nowTime);
            }else{
                int union1KillCount = 0;
                int union2KillCount = 0;
                List<Long> union1UserIdList = new ArrayList<>(union1Data.getMemberMap().keySet());
                List<Long> union2UserIdList = new ArrayList<>(union2Data.getMemberMap().keySet());
                for(CrossRankUnionWarKillRankData rankData : battleMatch.getKillRankList()){
                    if(union1UserIdList.contains(rankData.getUserId())){
                        union1KillCount = union1KillCount + rankData.getKillTimes();
                    }
                    if(union2UserIdList.contains(rankData.getUserId())){
                        union2KillCount = union2KillCount + rankData.getKillTimes();
                    }
                }
                if(union1KillCount > union2KillCount){
                    setWinUnion(battleMatch,battleMatch.getUnionId1(),nowTime);
                }else if(union1KillCount < union2KillCount){
                    setWinUnion(battleMatch,battleMatch.getUnionId2(),nowTime);
                }else{
                    if(union1Data.getUnionBaseInfo().getTotalEarnSpeed().compareTo(union2Data.getUnionBaseInfo().getTotalEarnSpeed()) >= 0){
                        setWinUnion(battleMatch,battleMatch.getUnionId1(),nowTime);
                    }else{
                        setWinUnion(battleMatch,battleMatch.getUnionId2(),nowTime);
                    }
                }
            }
        }
        if(battleMatch.getWinUnionId().equals(battleMatch.getUnionId2()) && union1Data != null){
            union1Data.setLoseTimes(union1Data.getLoseTimes() + 1);
            if(union1Data.getLoseTimes() >= config.getGameLoseCount()){
                union1Data.setDie(true);
            }
        }else if(battleMatch.getWinUnionId().equals(battleMatch.getUnionId1()) && union2Data != null){
            union2Data.setLoseTimes(union2Data.getLoseTimes() + 1);
            if(union2Data.getLoseTimes() >= config.getGameLoseCount()){
                union2Data.setDie(true);
            }
        }
        if(battleMatch.getWinUnionId().equals(battleMatch.getUnionId2()) && union2Data != null){
            union2Data.setWinTimes(union2Data.getWinTimes() + 1);
            for(long userId : union2Data.getMemberMap().keySet()){
                addConditionSync(userId,5,BigInteger.valueOf(union2Data.getWinTimes()),"");
            }
        }else if(battleMatch.getWinUnionId().equals(battleMatch.getUnionId1()) && union1Data != null){
            union1Data.setWinTimes(union1Data.getWinTimes() + 1);
            for(long userId : union1Data.getMemberMap().keySet()){
                addConditionSync(userId,5,BigInteger.valueOf(union1Data.getWinTimes()),"");
            }
        }

        RankUnionWarTimeConfig nextTimeConfig = config.getNextTimeConfig(battleMatch.getTurn());
        int nextDivision = config.getNextDivision(battleMatch.getDivision());
        if(nextTimeConfig != null){
            Map<Integer, Map<Integer, List<String>>> battleUnionIdMap = crossRankUnionWarData.getBattleUnionIdMap();
            if(!battleUnionIdMap.containsKey(nextTimeConfig.getSession())){
                battleUnionIdMap.put(nextTimeConfig.getSession(),new ConcurrentHashMap<>());
            }
            Map<Integer,List<String>> turnUnionMap = battleUnionIdMap.get(nextTimeConfig.getSession());
            //赢得晋级，输的留下
            if(!turnUnionMap.containsKey(nextDivision)){
                turnUnionMap.put(nextDivision,new ArrayList<>());
            }
            if(!turnUnionMap.containsKey(battleMatch.getDivision())){
                turnUnionMap.put(battleMatch.getDivision(),new ArrayList<>());
            }
            turnUnionMap.get(nextDivision).add(battleMatch.getWinUnionId());
            //连输四就淘汰了
            if(battleMatch.getWinUnionId().equals(battleMatch.getUnionId1())){
                if(union2Data != null && !union2Data.isDie()){
                    turnUnionMap.get(battleMatch.getDivision()).add(battleMatch.getUnionId2());
                }
            }else if(battleMatch.getWinUnionId().equals(battleMatch.getUnionId2())){
                if(union1Data != null && !union1Data.isDie()){
                    turnUnionMap.get(battleMatch.getDivision()).add(battleMatch.getUnionId1());
                }
            }
            crossRankUnionWarData.setBattleUnionIdMap(battleUnionIdMap);
        }
        if(!union1Data.isDie()){
            //不用每一轮都是拉门客了
//            sendGetAllPatrons(union1Data,battleMatch.getTurn()+1);
        }
        if(union2Data != null && !union2Data.isDie()){
            //不用每一轮都去拉门客了
//            sendGetAllPatrons(union2Data,battleMatch.getTurn()+1);
        }
        battleMatch.setStatus(2);
        addNeedUpdateMatch(battleMatch);
        addNeedSyncMatchWinList(battleMatch);
    }

    //优化,段位会掉
    private void battleStatueOver2(CrossRankUnionWarMatchData battleMatch){
        long nowTime = config.getTimeConfig(battleMatch.getTurn()).getEndTime();
        battlingMatchMap.remove(battleMatch.getGameNo());

        CrossRankUnionWarUnionData union1Data = getUnionData(battleMatch.getUnionId1());
        CrossRankUnionWarUnionData union2Data = getUnionData(battleMatch.getUnionId2());

        //当活动时间结束时，仍未分出胜负，则占点较多的商会获胜，若占点数量一致，则根据败敌数判断，败敌数较多的一方获胜，若败敌数也相同，则商会赚速较高的一方获得本场战斗的胜利
        if(StringUtils.isNullOrEmpty(battleMatch.getWinUnionId())){
            int union1WinCount = 0;
            int union2WinCount = 0;
            for(CrossRankUnionWarLineData lineData : battleMatch.getBattleLineMap().values()){
                //没有决出胜负的线路
                if(!StringUtils.isNullOrEmpty(lineData.getWinUnionId())){
                    if(lineData.getWinUnionId().equals(battleMatch.getUnionId1())){
                        union1WinCount++;
                    }else{
                        union2WinCount++;
                    }
                }
            }
            if(union1WinCount > union2WinCount){
                setWinUnion(battleMatch,battleMatch.getUnionId1(),nowTime);
            }else if(union1WinCount < union2WinCount){
                setWinUnion(battleMatch,battleMatch.getUnionId2(),nowTime);
            }else{
                int union1KillCount = 0;
                int union2KillCount = 0;
                List<Long> union1UserIdList = new ArrayList<>(union1Data.getMemberMap().keySet());
                List<Long> union2UserIdList = new ArrayList<>(union2Data.getMemberMap().keySet());
                for(CrossRankUnionWarKillRankData rankData : battleMatch.getKillRankList()){
                    if(union1UserIdList.contains(rankData.getUserId())){
                        union1KillCount = union1KillCount + rankData.getKillTimes();
                    }
                    if(union2UserIdList.contains(rankData.getUserId())){
                        union2KillCount = union2KillCount + rankData.getKillTimes();
                    }
                }
                if(union1KillCount > union2KillCount){
                    setWinUnion(battleMatch,battleMatch.getUnionId1(),nowTime);
                }else if(union1KillCount < union2KillCount){
                    setWinUnion(battleMatch,battleMatch.getUnionId2(),nowTime);
                }else{
                    if(union1Data.getUnionBaseInfo().getTotalEarnSpeed().compareTo(union2Data.getUnionBaseInfo().getTotalEarnSpeed()) >= 0){
                        setWinUnion(battleMatch,battleMatch.getUnionId1(),nowTime);
                    }else{
                        setWinUnion(battleMatch,battleMatch.getUnionId2(),nowTime);
                    }
                }
            }
        }
        if(battleMatch.getWinUnionId().equals(battleMatch.getUnionId2()) && union1Data != null){
            union1Data.setLoseTimes(union1Data.getLoseTimes() + 1);
            if(union1Data.getLoseTimes() >= config.getGameLoseCount()){
                union1Data.setDie(true);
            }
        }else if(battleMatch.getWinUnionId().equals(battleMatch.getUnionId1()) && union2Data != null){
            union2Data.setLoseTimes(union2Data.getLoseTimes() + 1);
            if(union2Data.getLoseTimes() >= config.getGameLoseCount()){
                union2Data.setDie(true);
            }
        }
        if(battleMatch.getWinUnionId().equals(battleMatch.getUnionId2()) && union2Data != null){
            union2Data.setWinTimes(union2Data.getWinTimes() + 1);
            for(long userId : union2Data.getMemberMap().keySet()){
                addConditionSync(userId,5,BigInteger.valueOf(union2Data.getWinTimes()),"");
            }
        }else if(battleMatch.getWinUnionId().equals(battleMatch.getUnionId1()) && union1Data != null){
            union1Data.setWinTimes(union1Data.getWinTimes() + 1);
            for(long userId : union1Data.getMemberMap().keySet()){
                addConditionSync(userId,5,BigInteger.valueOf(union1Data.getWinTimes()),"");
            }
        }

        RankUnionWarTimeConfig nextTimeConfig = config.getNextTimeConfig(battleMatch.getTurn());
        int nextDivision = config.getNextDivision(battleMatch.getDivision());
        int previousDivision = config.getPreviousDivision(battleMatch.getDivision());
        if(nextTimeConfig != null){
            Map<Integer, Map<Integer, List<String>>> battleUnionIdMap = crossRankUnionWarData.getBattleUnionIdMap();
            if(!battleUnionIdMap.containsKey(nextTimeConfig.getSession())){
                battleUnionIdMap.put(nextTimeConfig.getSession(),new ConcurrentHashMap<>());
            }
            Map<Integer,List<String>> turnUnionMap = battleUnionIdMap.get(nextTimeConfig.getSession());
            //赢得晋级，输的留下
            if(!turnUnionMap.containsKey(nextDivision)){
                turnUnionMap.put(nextDivision,new ArrayList<>());
            }
            if(!turnUnionMap.containsKey(previousDivision)){
                turnUnionMap.put(previousDivision,new ArrayList<>());
            }

            turnUnionMap.get(nextDivision).add(battleMatch.getWinUnionId());
            //连输四就淘汰了
            if(battleMatch.getWinUnionId().equals(battleMatch.getUnionId1())){
                if(union2Data != null && !union2Data.isDie()){
                    turnUnionMap.get(previousDivision).add(battleMatch.getUnionId2());
                }
            }else if(battleMatch.getWinUnionId().equals(battleMatch.getUnionId2())){
                if(union1Data != null && !union1Data.isDie()){
                    turnUnionMap.get(previousDivision).add(battleMatch.getUnionId1());
                }
            }
            crossRankUnionWarData.setBattleUnionIdMap(battleUnionIdMap);
        }
        if(!union1Data.isDie()){
            //不用每一轮都是拉门客了
//            sendGetAllPatrons(union1Data,battleMatch.getTurn()+1);
        }
        if(union2Data != null && !union2Data.isDie()){
            //不用每一轮都去拉门客了
//            sendGetAllPatrons(union2Data,battleMatch.getTurn()+1);
        }
        battleMatch.setStatus(2);
        addNeedUpdateMatch(battleMatch);
        addNeedSyncMatchWinList(battleMatch);
    }

    /**
     * 比赛结束玩家积分变化
     * @param unionUid
     * @param notifyType
     */
    public void changeUnionActivityValue(String unionUid, int notifyType) {
        CrossRankUnionWarUnionData unionData = getUnionData(unionUid);
        if(unionData != null){
            Map<Long,Integer> memberMap = new ConcurrentHashMap<>();
            for(long userId : unionData.getMemberMap().keySet()){
                if(!unionData.getMemberMap().get(userId).isQuit()){
                    memberMap.put(userId,unionData.getMemberMap().get(userId).getPosition());
                }
            }
            CrossUnionActivityDataMgr.changeUserData(
                    getActivityId(),eGamePlayerEventType.RankUnionWarUnionScoreRank.getValue(),BigInteger.valueOf(unionData.getScore()),unionUid
                    ,notifyType,memberMap,unionData.getUnionBaseInfo().getServerId(),unionData.getUnionBaseInfo());
        }
    }

    /**
     * 设置比赛胜利的商会，并且加上分数
     * @param battleMatch
     * @param winUnionId
     * @param nowTime
     */
    private void setWinUnion(CrossRankUnionWarMatchData battleMatch,String winUnionId,long nowTime){
        battleMatch.setWinUnionId(winUnionId);
        battleMatch.setWinTime(nowTime);
        RankUnionWarDivisionConfig division = config.getDivisionConfig(battleMatch.getDivision());
        List<Integer> winScoreList = division.getWinScoreList();
        List<Integer> loseScoreList = division.getLoseScoreList();
        int winScore = 0;
        int loseScore = 0;
        if(winScoreList.size() > battleMatch.getTurn() - 1){
            winScore = winScoreList.get(battleMatch.getTurn() - 1);
        }else{
            logger.error("巅峰{},胜利分数第{}轮没有配置",getActivityId(),battleMatch.getTurn());
        }
        if(loseScoreList.size() > battleMatch.getTurn() - 1){
            loseScore = loseScoreList.get(battleMatch.getTurn() - 1);
        }else{
            logger.error("巅峰{},失败分数第{}轮没有配置",getActivityId(),battleMatch.getTurn());
        }
        int winWinLineCount = 0;
        int loseWinLineCount = 0;
        for(CrossRankUnionWarLineData battleLine : battleMatch.getBattleLineMap().values()){
            if(battleLine.getWinUnionId().equals(winUnionId)){
                winWinLineCount++;
            }else if(!StringUtils.isNullOrEmpty(battleLine.getWinUnionId()) && !battleLine.getWinUnionId().equals(winUnionId)){
                loseWinLineCount++;
            }
        }
        CrossRankUnionWarUnionData winUnionData = getUnionData(winUnionId);
        winUnionData.setScore(winUnionData.getScore() + winScore + winWinLineCount * config.getLineWinAddScore());
        CrossRankUnionWarUnionData loseUnionData = null;
        if(battleMatch.getUnionId1().equals(winUnionId)){
            if(!StringUtils.isNullOrEmpty(battleMatch.getUnionId2())){
                loseUnionData = getUnionData(battleMatch.getUnionId2());
                loseUnionData.setScore(loseUnionData.getScore() + loseScore + loseWinLineCount * config.getLineWinAddScore());
            }
        }else{
            loseUnionData = getUnionData(battleMatch.getUnionId1());
            loseUnionData.setScore(loseUnionData.getScore() + loseScore + loseWinLineCount * config.getLineWinAddScore());
        }
        CrossRankUnionWarGambleData gambleData = gambleMap.get(battleMatch.getTurn());
        if(gambleData.getGameNoMap().containsKey(battleMatch.getGameNo())){
            List<String> winUnionList = gambleData.getWinUnionIdList();
            winUnionList.add(winUnionId);
        }
        if(winUnionData != null){
            changeUnionActivityValue(winUnionId,UnionRiseRankArgs.NOTIFY_TYPE_NORMAL);
        }
        if(loseUnionData != null){
            changeUnionActivityValue(loseUnionData.getUnionId(),UnionRiseRankArgs.NOTIFY_TYPE_NORMAL);
        }

        /*for(CrossRankUnionWarMemberData memberData : winUnionData.getMemberMap().values()){
            addConditionSync(memberData.getUserId(),3,BigInteger.valueOf(winUnionData.getScore()),"");
        }
        if(loseUnionData != null){
            for(CrossRankUnionWarMemberData memberData : loseUnionData.getMemberMap().values()){
                addConditionSync(memberData.getUserId(),3,BigInteger.valueOf(loseUnionData.getScore()),"");
            }
        }*/
    }

    /**
     * 结束比赛清除掉数据
     * @param battleMatch
     */
    private void clearBattleMatchData(CrossRankUnionWarMatchData battleMatch){
        if(battleMatch.getStatus() != 2)return;
        logger.error("巅峰{}活动比赛结束gameNo:{}清除活动战报，清除派遣门客数据，清除对战门客数据,且加上没死的门客算成的击杀"
                ,getActivityId(),battleMatch.getGameNo());
        //战报清掉
        battleMatch.getNoticeList().clear();
        //出战顺序清掉
        battleMatch.getWaitPatronsMap().clear();
        //缓存清掉
        battleMatch.getReadyPatronsSortMap().clear();
        //没死的加入击杀榜单
        for(CrossRankUnionWarLineData lineData : battleMatch.getBattleLineMap().values()){
            for(String unionId : lineData.getBattlePatronsMap().keySet()){
                Map<Integer, CrossRankUnionWarBattlePatronData> patronDataMap = lineData.getBattlePatronsMap().get(unionId);
                for(CrossRankUnionWarBattlePatronData patronData : patronDataMap.values()){
                    if(!patronData.isDie()){
                        addKillRank(patronData);
                    }
                }
            }
            //每一条线清掉
            lineData.getBattlePatronsMap().clear();
        }
        barrageList.remove(battleMatch.getGameNo());
    }

    /**
     * 把有复活次数的门客复活 对应战线上去必须死了才能复活
     * @param battlePatronData
     * @param dieTime
     */
    private void joinRevivePatronToBattleLine(CrossRankUnionWarBattlePatronData battlePatronData,long dieTime){
        CrossRankUnionWarMatchData matchData = getIngGameNoMatch(battlePatronData.getGameNo());
        if(matchData != null){
            Map<Long, Map<Integer, CrossRankUnionWarWaitPatronData>> waitPatronsMap = new ConcurrentHashMap<>(matchData.getWaitPatronsMap());
            if(waitPatronsMap.containsKey(battlePatronData.getUserId())){
                CrossRankUnionWarWaitPatronData waitPatronData = waitPatronsMap.get(battlePatronData.getUserId()).get(battlePatronData.getPatronId());
                joinRevivePatronToBattleLine(waitPatronData,matchData.getTurn(),dieTime);
            }else{
                logger.error("巅峰{}活动出现复活门客不在备战列表的gameNo:{},userId:{},patronsId:{}",getActivityId(),battlePatronData.getGameNo(),battlePatronData.getUserId(),battlePatronData.getPatronId());
            }
        }
    }

    private void joinRevivePatronToBattleLine(CrossRankUnionWarWaitPatronData waitPatronData,int turn,long dieTime){
        CrossRankUnionWarMatchData matchData = getIngGameNoMatch(waitPatronData.getGameNo());
        CrossRankUnionWarUnionData unionData = getUnionData(waitPatronData.getUserId());
        if (matchData != null && unionData != null){
            CrossRankUnionWarPatronData patronInfoData = getPatronsInfo(waitPatronData.getUserId(),turn,waitPatronData.getPatronId());
            if(patronInfoData != null){
                //玩家复活门客和自动战斗中死了门客有复活次数复活
                /*synchronized (patronInfoData){
                    //手动复活和自动不会并发了，比赛加锁了，如果很卡了就加回来，到battleLine(中的getStartWaitTime() == 0的地方删掉
                }*/
                //出战次数减去一次免费的小于买活次数说明能复活
                if(waitPatronData.getBattleTimes() - 1 < patronInfoData.getBuyMap().getOrDefault(waitPatronData.getGameNo(),0)){
                    //死亡次数等于出战次数，说明场上死光了
                    int dieTimes = getPatronsDieTimes(waitPatronData);
                    if(dieTimes == waitPatronData.getBattleTimes()){
                        logger.info("巅峰{}玩家{}门客{}重生",getActivityId(),waitPatronData.getUserId(),waitPatronData.getPatronId());
                        addPatronsToBattleLineVersion2(matchData.getBattleLineMap().get(waitPatronData.getLine()),waitPatronData,dieTime,true);
                        addNeedSyncMatchCountList(matchData);
                    }
                }
            }
        }
    }

    /**
     * 获取玩家身上的原始门客信息
     * @param userId
     * @param turn
     * @param patronsId
     * @return
     */
    private CrossRankUnionWarPatronData getPatronsInfo(long userId, int turn, int patronsId){
        CrossRankUnionWarUnionData unionData = getUnionData(userId);
        if(unionData != null){
            if(unionData.getMemberMap().containsKey(userId)){
                Map<Integer, CrossRankUnionWarPatronData> patronsMap = unionData.getMemberMap().get(userId).getPatronDataMap(turn);
                if(patronsMap != null){
                    if(patronsMap.containsKey(patronsId)){
                        return patronsMap.get(patronsId);
                    }
                }
            }
        }
        return null;
    }

    private CrossRankUnionWarPatronData getPatronsInfo(CrossRankUnionWarWaitPatronData waitPatronData){
        CrossRankUnionWarMatchData matchData = getIngGameNoMatch(waitPatronData.getGameNo());
        CrossRankUnionWarUnionData unionData = getUnionData(waitPatronData.getUserId());
        if(unionData != null && matchData != null){
            if(unionData.getMemberMap().containsKey(waitPatronData.getUserId())){
                Map<Integer, CrossRankUnionWarPatronData> patronsMap = unionData.getMemberMap().get(waitPatronData.getUserId()).getPatronDataMap(matchData.getTurn());
                if(patronsMap != null){
                    if(patronsMap.containsKey(waitPatronData.getPatronId())){
                        return patronsMap.get(waitPatronData.getPatronId());
                    }
                }
            }
        }
        return null;
    }

    /**
     * 获取备战门客
     * @param gameNo
     * @param userId
     * @param patronsId
     * @return
     */
    private CrossRankUnionWarWaitPatronData getWaitPatrons(int gameNo,long userId,int patronsId){
        CrossRankUnionWarMatchData battleMatch = getGameNoMatch(gameNo);
        if(battleMatch == null){
            return null;
        }
        Map<Long, Map<Integer, CrossRankUnionWarWaitPatronData>> userWaitPatronsMap = new ConcurrentHashMap<>(battleMatch.getWaitPatronsMap());
        if(!userWaitPatronsMap.containsKey(userId)){
            return null;
        }
        Map<Integer, CrossRankUnionWarWaitPatronData> patronDataMap = userWaitPatronsMap.get(userId);
        if(patronDataMap.containsKey(patronsId)){
            return patronDataMap.get(patronsId);
        }
        return null;
    }

    /**
     * 处理一个战斗的进度,门客出来打
     * @param battleMatch
     * @param nowTime
     */
    private void battleMatch(CrossRankUnionWarMatchData battleMatch,long nowTime){
        boolean isSyncWin = false;
        if(!StringUtils.isNullOrEmpty(battleMatch.getWinUnionId())){
            return;
        }
        RankUnionWarTimeConfig timeConfig = config.getTimeConfig(battleMatch.getTurn());
        long startBattleTime = timeConfig.getStartBattleTime();
        int battleInterval = config.getBattleInterval() * 1000;
        if(nowTime < startBattleTime){
            return;
        }
        long battleTime = battleMatch.getBattleTime();
        long nextBattleTime = startBattleTime + (nowTime - startBattleTime)/battleInterval * battleInterval;
        if(nextBattleTime != battleMatch.getBattleTime()){
            battleMatch.setBattleTime(nextBattleTime);
        }
        if(StringUtils.isNullOrEmpty(battleMatch.getUnionId2())){
            for(CrossRankUnionWarLineData battleLine : battleMatch.getBattleLineMap().values()){
                setLineWinUnion(battleMatch,battleLine,battleLine.getUnionId1(),0);
            }
            setWinUnion(battleMatch,battleMatch.getUnionId1(),nowTime);
            return;
        }
        Map<Integer, CrossRankUnionWarLineData> battleLineMap = battleMatch.getBattleLineMap();
        for(CrossRankUnionWarLineData battleLine : battleLineMap.values()){
            if(!StringUtils.isNullOrEmpty(battleLine.getWinUnionId()))continue;
            battleLine(battleLine,startBattleTime,battleTime);
            addNeedUpdateLine(battleLine);
            if(checkWaitTime(battleMatch,battleLine,nowTime)){
                isSyncWin = true;
            }
        }
        //排序一下击杀榜
        battleMatch.sortRankList();
        int win1Count = 0;
        int win2Count = 0;
        for(CrossRankUnionWarLineData battleLine : battleLineMap.values()){
            if(battleLine.getWinUnionId().equals(battleLine.getUnionId1())){
                win1Count++;
            }else if(battleLine.getWinUnionId().equals(battleLine.getUnionId2())){
                win2Count++;
            }
        }
        if(win1Count >= 3){
            setWinUnion(battleMatch,battleMatch.getUnionId1(),nowTime);
            isSyncWin = true;
        }
        if(win2Count >= 3){
            setWinUnion(battleMatch,battleMatch.getUnionId2(),nowTime);
            isSyncWin = true;
        }
        addNeedUpdateMatch(battleMatch);
        if(isSyncWin){
            addNeedSyncMatchWinList(battleMatch);
        }
    }

    //把所有的碰撞时间打印出来
    private void printDebugTime(){
        int babatime = config.getTurnBattleStartSec() * 1000;
        Map<Long, Long> battleTimeMap = config.getBattleTimeMap();
        List<Long> passTimeList = new ArrayList<>(battleTimeMap.keySet());
        Collections.sort(passTimeList);
        long nowTime = passTimeList.get(passTimeList.size() - 1);
        long nextBattleTime = babatime;
        logger.error("战斗时间{}",nextBattleTime);
        for(long passTime : passTimeList){
            long battleInterval = battleTimeMap.get(passTime);
            if(nowTime < passTime){
                long goTime = (nowTime - nextBattleTime)/battleInterval * battleInterval;
                nextBattleTime = nextBattleTime + goTime;
                logger.error("战斗时间{},碰撞时间{}",nextBattleTime,battleInterval);
                break;
            }else if(nowTime > passTime){
                long goTime = (passTime - nextBattleTime)/battleInterval * battleInterval;
                nextBattleTime = nextBattleTime + goTime;
                logger.error("战斗时间{},碰撞时间{}",nextBattleTime,battleInterval);
            }
            //最后的卡零界点用上一次战斗的碰撞时间，比如过了200从3的碰撞变2，现在198秒碰完就是201，然后才是203碰
            if(nextBattleTime < passTime){
                if(nextBattleTime + battleInterval <= nowTime){
                    nextBattleTime = nextBattleTime + battleInterval;
                    logger.error("战斗时间{},碰撞时间{}",nextBattleTime,battleInterval);
                }else{
                    break;
                }
            }
        }
    }

    /**
     * 优化了战斗碰撞时间，从一开始的一直是多少秒变成不同战斗时间段战斗碰撞时间不一样的
     * */
    private long getNextBattleTime(int turn,long nowTime){
        RankUnionWarTimeConfig timeConfig = config.getTimeConfig(turn);
        if(nowTime <= timeConfig.getStartBattleTime()){
            return timeConfig.getStartBattleTime();
        }
        Map<Long, Long> battleTimeMap = config.getBattleTimeMap();
        List<Long> passTimeList = new ArrayList<>(battleTimeMap.keySet());
        Collections.sort(passTimeList);
        if(passTimeList.get(passTimeList.size() - 1) < timeConfig.getDurTime() * 60 * 1000){
            battleTimeMap.put(1000L * timeConfig.getDurTime() * 60,battleTimeMap.get(passTimeList.get(passTimeList.size() - 1)));
            passTimeList.add(1000L * timeConfig.getDurTime() * 60);
        }
        long nextBattleTime = timeConfig.getStartBattleTime();
        for(long passTime : passTimeList){
            long battleInterval = battleTimeMap.get(passTime);
            if(nowTime < timeConfig.getStartTime() + passTime){
                long goTime = (nowTime - nextBattleTime)/battleInterval * battleInterval;
                nextBattleTime = nextBattleTime + goTime;
                break;
            }else if(nowTime > timeConfig.getStartTime() + passTime){
                long goTime = (timeConfig.getStartTime() + passTime - nextBattleTime)/battleInterval * battleInterval;
                nextBattleTime = nextBattleTime + goTime;
//                logger.error("{}阶段零界时间{}",passTime,nextBattleTime);
            }
            //最后的卡零界点用上一次战斗的碰撞时间，比如过了200从3的碰撞变2，现在198秒碰完就是201，然后才是203碰
            if(nextBattleTime < timeConfig.getStartTime() + passTime){
                if(nextBattleTime + battleInterval <= nowTime){
                    nextBattleTime = nextBattleTime + battleInterval;
                }else{
                    break;
                }
            }
        }
        return nextBattleTime;
    }

    private void battleMatch2(CrossRankUnionWarMatchData battleMatch,long nowTime){
        boolean isSyncWin = false;
        if(!StringUtils.isNullOrEmpty(battleMatch.getWinUnionId())){
            return;
        }
        RankUnionWarTimeConfig timeConfig = config.getTimeConfig(battleMatch.getTurn());
        long startBattleTime = timeConfig.getStartBattleTime();
        if(nowTime < startBattleTime){
            return;
        }
        long battleTime = battleMatch.getBattleTime();
        long nextBattleTime = getNextBattleTime(battleMatch.getTurn(),nowTime);
        if(nextBattleTime != battleMatch.getBattleTime()){
            battleMatch.setBattleTime(nextBattleTime);
        }
        if(StringUtils.isNullOrEmpty(battleMatch.getUnionId2())){
            for(CrossRankUnionWarLineData battleLine : battleMatch.getBattleLineMap().values()){
                setLineWinUnion(battleMatch,battleLine,battleLine.getUnionId1(),0);
            }
            setWinUnion(battleMatch,battleMatch.getUnionId1(),nowTime);
            return;
        }
        Map<Integer, CrossRankUnionWarLineData> battleLineMap = battleMatch.getBattleLineMap();
        for(CrossRankUnionWarLineData battleLine : battleLineMap.values()){
            if(!StringUtils.isNullOrEmpty(battleLine.getWinUnionId()))continue;
            battleLine2(battleMatch.getTurn(),battleLine,startBattleTime,battleTime);
            addNeedUpdateLine(battleLine);
            if(checkWaitTime(battleMatch,battleLine,nowTime)){
                isSyncWin = true;
            }
        }
        //排序一下击杀榜
        battleMatch.sortRankList();
        int win1Count = 0;
        int win2Count = 0;
        for(CrossRankUnionWarLineData battleLine : battleLineMap.values()){
            if(battleLine.getWinUnionId().equals(battleLine.getUnionId1())){
                win1Count++;
            }else if(battleLine.getWinUnionId().equals(battleLine.getUnionId2())){
                win2Count++;
            }
        }
        //改成必须五条线分出胜负
        if(win1Count + win2Count >= 5){
            if(win1Count > win2Count){
                setWinUnion(battleMatch,battleMatch.getUnionId1(),nowTime);
                isSyncWin = true;
            }else{
                setWinUnion(battleMatch,battleMatch.getUnionId2(),nowTime);
                isSyncWin = true;
            }
        }
        addNeedUpdateMatch(battleMatch);
        if(isSyncWin){
            addNeedSyncMatchWinList(battleMatch);
        }
    }

    //gameNo,line,battleTime
    private Map<Integer,Map<Integer,Map<Long,RankUnionWarDebugBattleData>>> debugBattleMap = new ConcurrentHashMap<>();

    public void debugBattle(long serverId, long userId, RankUnionWarProto.DeBugRankUnionWarBattlePatronsReqMsg reqMsg) {
        RankUnionWarProto.DeBugRankUnionWarBattlePatronsRespMsg.Builder respMsg = RankUnionWarProto.DeBugRankUnionWarBattlePatronsRespMsg.newBuilder();
        int gameNo = reqMsg.getGameNo();
        long battleTime = reqMsg.getBattleTime();
        CrossRankUnionWarMatchData gameMatch = getGameNoMatch(gameNo);
        if(debugBattleMap.containsKey(gameNo)){
            for(Map<Long,RankUnionWarDebugBattleData> lineBattleTimeMap : debugBattleMap.get(gameNo).values()){
                if(lineBattleTimeMap.containsKey(battleTime)){
                    RankUnionWarDebugBattleData debugData = lineBattleTimeMap.get(battleTime);
                    RankUnionWarProto.DeBugRankUnionWarBattleTimeMsg.Builder timeMsg = RankUnionWarProto.DeBugRankUnionWarBattleTimeMsg.newBuilder();
                    timeMsg.setLine(debugData.getLine());
                    timeMsg.addBeginBool(debugData.getBeginBool1());
                    timeMsg.addBeginBool(debugData.getBeginBool2());

                    timeMsg.addEndBool(debugData.getEndBool1());
                    timeMsg.addEndBool(debugData.getEndBool2());

                    timeMsg.addLastBool(debugData.getLastBool1());
                    timeMsg.addLastBool(debugData.getLastBool2());

                    timeMsg.addPatronsId(debugData.getPatronsId1());
                    timeMsg.addPatronsId(debugData.getPatronsId2());

                    timeMsg.addPatronsNo(debugData.getPatronsNo1());
                    timeMsg.addPatronsNo(debugData.getPatronsNo2());

                    timeMsg.addPindex(debugData.getpIndex1());
                    timeMsg.addPindex(debugData.getpIndex2());

                    timeMsg.addOccupyTime(debugData.getOccupyTime1());
                    timeMsg.addOccupyTime(debugData.getOccupyTime2());

                    timeMsg.addKillTimes(debugData.getKillTime1());
                    timeMsg.addKillTimes(debugData.getKillTime2());
                    respMsg.addLine(timeMsg);
                }else {
                    if(gameMatch != null && gameMatch.getBattleTime() < reqMsg.getBattleTime()){
                        logger.error("巅峰{},客户端来请求还没开始打的时间记录{}",getActivityId(),reqMsg.getBattleTime());
                    }else{
                        logger.error("巅峰{},客户端来请求开始打的时间记录却没有{}",getActivityId(),reqMsg.getBattleTime());
                    }
                }
            }
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_BATTLE_DEBUG, respMsg);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
    }

    private void addDebugBattleData(CrossRankUnionWarBattlePatronData union1Patron,CrossRankUnionWarBattlePatronData union2Patron,long battleTime,CrossRankUnionWarLineData battleLine){
        RankUnionWarDebugBattleData data = new RankUnionWarDebugBattleData();
        data.setBattleTime(battleTime);
        data.setGameNo(battleLine.getGameNo());
        data.setLine(battleLine.getLine());
        if(union1Patron != null){
            data.setBeginBool1(union1Patron.getBool().longValue());
            data.setEndBool1(union1Patron.getBool().longValue());
            data.setLastBool1(union1Patron.getBool().longValue());
            data.setPatronsId1(union1Patron.getPatronId());
            data.setPatronsNo1(union1Patron.getPatronsNo());
            data.setpIndex1(union1Patron.getLineIndex());
            data.setKillTime1(union1Patron.getKillTimes());
        }
        if(union2Patron != null){
            data.setBeginBool2(union2Patron.getBool().longValue());
            data.setEndBool2(union2Patron.getBool().longValue());
            data.setLastBool2(union2Patron.getBool().longValue());
            data.setPatronsId2(union2Patron.getPatronId());
            data.setPatronsNo2(union2Patron.getPatronsNo());
            data.setpIndex2(union2Patron.getLineIndex());
            data.setKillTime2(union2Patron.getKillTimes());
        }
        if(union1Patron != null && union2Patron != null){
            int debuff = config.getPatronsWinDebuff();
            //胜利达到多少场次就要退场了
            int winMaxTimes = config.getPatronsWinMaxCount();
            if(union1Patron.getBool().compareTo(union2Patron.getBool()) >= 0){
                BigInteger sbBool = union1Patron.getBool().subtract(union2Patron.getBool());
                data.setEndBool1(sbBool.longValue());
                data.setEndBool2(0);

                BigInteger subBool = sbBool.multiply(BigInteger.valueOf(debuff)).divide(BigInteger.valueOf(1000));
                BigInteger endBool = sbBool.subtract(subBool);
                data.setLastBool1(endBool.longValue());
                data.setLastBool2(0);
                if(union1Patron.getKillTimes() + 1 >= winMaxTimes){
                    data.setLastBool1(0);
                }
                data.setKillTime1(union1Patron.getKillTimes() + 1);
                data.setKillTime2(union2Patron.getKillTimes());
            }else{
                BigInteger sbBool = union2Patron.getBool().subtract(union1Patron.getBool());
                data.setEndBool1(0);
                data.setEndBool2(sbBool.longValue());
                BigInteger subBool = sbBool.multiply(BigInteger.valueOf(debuff)).divide(BigInteger.valueOf(1000));
                BigInteger endBool = sbBool.subtract(subBool);
                data.setLastBool1(0);
                data.setLastBool2(endBool.longValue());
                if(union2Patron.getKillTimes() + 1 >= winMaxTimes){
                    data.setLastBool2(0);
                }
                data.setKillTime1(union1Patron.getKillTimes());
                data.setKillTime2(union2Patron.getKillTimes() + 1);
            }
        }

        if(battleLine.getUnion2StartWaitTime() != 0){
            data.setOccupyTime1((battleTime - battleLine.getUnion2StartWaitTime() + battleLine.getUnion2WaitTime()));
        }else{
            data.setOccupyTime1((battleLine.getUnion2WaitTime()));
        }

        if(battleLine.getUnion1StartWaitTime() != 0){
            data.setOccupyTime2((battleTime - battleLine.getUnion1StartWaitTime() + battleLine.getUnion1WaitTime()));
        }else{
            data.setOccupyTime2((battleLine.getUnion1WaitTime()));
        }
        synchronized (debugBattleMap){
            if(!debugBattleMap.containsKey(data.getGameNo())){
                Map<Integer,Map<Long,RankUnionWarDebugBattleData>> lineMap = new ConcurrentHashMap<>();
                for(int line = 1; line <= 5;line++){
                    lineMap.put(line,new ConcurrentHashMap<>());
                }
                debugBattleMap.put(data.getGameNo(),lineMap);
            }
        }
        debugBattleMap.get(data.getGameNo()).get(data.getLine()).put(data.getBattleTime(),data);
    }

    //两个门客战斗，无限递归,返回最近一个活着的门客的最后战斗时间
    //返回上次计算到哪里，如果返回的时间和当前时间差值大于设定只就结束游戏了
    //正常的按照时间顺序的战斗
    private void battleLine(CrossRankUnionWarLineData battleLine,long startTime,long battleTime){
        Map<String, Map<Integer, CrossRankUnionWarBattlePatronData>> unionLineMap = battleLine.getBattlePatronsMap();
        Map<Integer, CrossRankUnionWarBattlePatronData> union1PatronsMap = unionLineMap.get(battleLine.getUnionId1());
        Map<Integer, CrossRankUnionWarBattlePatronData> union2PatronsMap = unionLineMap.get(battleLine.getUnionId2());
        CrossRankUnionWarBattlePatronData union1Patron = getAlivePatron(union1PatronsMap);
        CrossRankUnionWarBattlePatronData union2Patron = getAlivePatron(union2PatronsMap);

        int battleInterval = config.getBattleInterval() * 1000;
        long lastBattleTime = battleLine.getLastBattleTime();
        if(battleTime - lastBattleTime >= battleInterval){
            if(lastBattleTime == 0){
                lastBattleTime = startTime;
            }else{
                lastBattleTime = lastBattleTime + battleInterval;
            }
            battleLine.setLastBattleTime(lastBattleTime);
            //复活时间可能都还没计算上一次，会导致虽然后面复活的却去前面打了，和客户端不一致
            if(union1Patron != null && union1Patron.getSendTime() > lastBattleTime){
                union1Patron = null;
            }
            if(union2Patron != null && union2Patron.getSendTime() > lastBattleTime){
                union2Patron = null;
            }
            addDebugBattleData(union1Patron,union2Patron,lastBattleTime,battleLine);
            if(union1Patron != null && union2Patron != null){
                if(union1Patron.getBool().compareTo(union2Patron.getBool()) > 0){
                    dealWinPatrons(union1Patron,union1Patron.getBool().subtract(union2Patron.getBool()),lastBattleTime,battleLine.getUnionId2());
                    union2Patron.setBool(BigInteger.ZERO);
                    setPatronsDie(union2Patron,battleLine.getUnionId1(),lastBattleTime);
                    addKillRank(union1Patron);
                }else if(union1Patron.getBool().compareTo(union2Patron.getBool()) == 0){
                    union1Patron.setBool(BigInteger.ZERO);
                    setPatronsDie(union1Patron,battleLine.getUnionId2(),lastBattleTime);
                    addKillRank(union1Patron);
                    union2Patron.setBool(BigInteger.ZERO);
                    setPatronsDie(union2Patron,battleLine.getUnionId1(),lastBattleTime);
                    addKillRank(union2Patron);
                }else{
                    dealWinPatrons(union2Patron,union2Patron.getBool().subtract(union1Patron.getBool()),lastBattleTime,battleLine.getUnionId1());
                    union1Patron.setBool(BigInteger.ZERO);
                    setPatronsDie(union1Patron,battleLine.getUnionId2(),lastBattleTime);
                    addKillRank(union2Patron);

                }
                //有可能次数暴毙了两边都没人了
                if(getAlivePatron(union2PatronsMap) == null && getAlivePatron(union1PatronsMap) != null){
                    battleLine.setUnion2StartWaitTime(lastBattleTime);
                }
                if(getAlivePatron(union1PatronsMap) == null && getAlivePatron(union2PatronsMap) != null){
                    battleLine.setUnion1StartWaitTime(lastBattleTime);
                }
            }else if(union1Patron != null){
                battleLine.setLastBattleTime(battleTime);
                if(battleLine.getUnion2StartWaitTime() == 0 && getAlivePatron(union2PatronsMap) == null){
                    battleLine.setUnion2StartWaitTime(lastBattleTime);
                }
                return;
            }else if(union2Patron != null){
                battleLine.setLastBattleTime(battleTime);
                if(battleLine.getUnion1StartWaitTime() == 0 && getAlivePatron(union1PatronsMap) == null){
                    battleLine.setUnion1StartWaitTime(lastBattleTime);
                }
                return;
            }else{
                battleLine.setLastBattleTime(battleTime);
                return;
            }
        }else{
            return;
        }
        battleLine(battleLine,startTime,battleTime);
    }

    //优化了战斗时间都不一样了
    private void battleLine2(int turn,CrossRankUnionWarLineData battleLine,long startTime,long battleTime){
        Map<String, Map<Integer, CrossRankUnionWarBattlePatronData>> unionLineMap = battleLine.getBattlePatronsMap();
        Map<Integer, CrossRankUnionWarBattlePatronData> union1PatronsMap = unionLineMap.get(battleLine.getUnionId1());
        Map<Integer, CrossRankUnionWarBattlePatronData> union2PatronsMap = unionLineMap.get(battleLine.getUnionId2());
        CrossRankUnionWarBattlePatronData union1Patron = getAlivePatron(union1PatronsMap);
        CrossRankUnionWarBattlePatronData union2Patron = getAlivePatron(union2PatronsMap);

        long lastBattleTime = battleLine.getLastBattleTime();
        long battleInterval;
        if(lastBattleTime == 0){
            battleInterval = config.getBattleIntervalTime(turn,startTime);
        }else{
            battleInterval = config.getBattleIntervalTime(turn,lastBattleTime);
        }
        if(battleTime - lastBattleTime >= battleInterval){
            if(lastBattleTime == 0){
                lastBattleTime = startTime;
            }else{
                lastBattleTime = lastBattleTime + battleInterval;
            }
            battleLine.setLastBattleTime(lastBattleTime);
            //复活时间可能都还没计算上一次，会导致虽然后面复活的却去前面打了，和客户端不一致
            if(union1Patron != null && union1Patron.getSendTime() > lastBattleTime){
                union1Patron = null;
            }
            if(union2Patron != null && union2Patron.getSendTime() > lastBattleTime){
                union2Patron = null;
            }
            addDebugBattleData(union1Patron,union2Patron,lastBattleTime,battleLine);
            if(union1Patron != null && union2Patron != null){
                if(union1Patron.getBool().compareTo(union2Patron.getBool()) > 0){
                    dealWinPatrons(union1Patron,union1Patron.getBool().subtract(union2Patron.getBool()),lastBattleTime,battleLine.getUnionId2());
                    union2Patron.setBool(BigInteger.ZERO);
                    setPatronsDie(union2Patron,battleLine.getUnionId1(),lastBattleTime);
                    addKillRank(union1Patron);
                }else if(union1Patron.getBool().compareTo(union2Patron.getBool()) == 0){
                    union1Patron.setBool(BigInteger.ZERO);
                    setPatronsDie(union1Patron,battleLine.getUnionId2(),lastBattleTime);
                    addKillRank(union1Patron);
                    union2Patron.setBool(BigInteger.ZERO);
                    setPatronsDie(union2Patron,battleLine.getUnionId1(),lastBattleTime);
                    addKillRank(union2Patron);
                }else{
                    dealWinPatrons(union2Patron,union2Patron.getBool().subtract(union1Patron.getBool()),lastBattleTime,battleLine.getUnionId1());
                    union1Patron.setBool(BigInteger.ZERO);
                    setPatronsDie(union1Patron,battleLine.getUnionId2(),lastBattleTime);
                    addKillRank(union2Patron);

                }
                //有可能次数暴毙了两边都没人了
                if(getAlivePatron(union2PatronsMap) == null && getAlivePatron(union1PatronsMap) != null){
                    battleLine.setUnion2StartWaitTime(lastBattleTime);
                }
                if(getAlivePatron(union1PatronsMap) == null && getAlivePatron(union2PatronsMap) != null){
                    battleLine.setUnion1StartWaitTime(lastBattleTime);
                }
            }else if(union1Patron != null){
                battleLine.setLastBattleTime(battleTime);
                if(battleLine.getUnion2StartWaitTime() == 0 && getAlivePatron(union2PatronsMap) == null){
                    battleLine.setUnion2StartWaitTime(lastBattleTime);
                }
                return;
            }else if(union2Patron != null){
                battleLine.setLastBattleTime(battleTime);
                if(battleLine.getUnion1StartWaitTime() == 0 && getAlivePatron(union1PatronsMap) == null){
                    battleLine.setUnion1StartWaitTime(lastBattleTime);
                }
                return;
            }else{
                battleLine.setLastBattleTime(battleTime);
                return;
            }
        }else{
            return;
        }
        battleLine2(turn,battleLine,startTime,battleTime);
    }

    /**
     * 门客战死，被打死或者同归于尽或者杀太多人了都会死，死了要看杀了多少个人上战报
     * @param patrons
     * @param enemyUnionId
     * @param dieTime
     */
    private void setPatronsDie(CrossRankUnionWarBattlePatronData patrons,String enemyUnionId,long dieTime){
        patrons.setDie(true);
        CrossRankUnionWarMatchData match = getGameNoMatch(patrons.getGameNo());
        if(match == null)return;
        joinRevivePatronToBattleLine(patrons,dieTime);
        if(patrons.getKillTimes() >= config.getKillNumNotice()){
            List<CrossRankUnionWarNoticeData> noticeDataList = match.getNoticeList();
            CrossRankUnionWarNoticeData noticeData = new CrossRankUnionWarNoticeData();
            noticeData.setGameNo(match.getGameNo());
            noticeData.setKillTimes(patrons.getKillTimes());
            noticeData.setPatronId(patrons.getPatronId());
            noticeData.setUserId(patrons.getUserId());
            noticeData.setNoticeTime(dieTime);
            noticeData.setEnemyUnionId(enemyUnionId);
            if(noticeDataList.size() > 0){
                noticeData.setNo(noticeDataList.get(noticeDataList.size() - 1).getNo() + 1);
            }else{
                noticeData.setNo(1);
            }
            noticeDataList.add(noticeData);
            if(noticeDataList.size() > 50){
                noticeDataList.remove(0);
            }
            addNeedSyncNoticeMap(noticeData);
        }
        addNeedUpdateBattlePatrons(patrons);
    }

    //设置胜利队伍，超过3个队伍就不设置了
    private void setLineWinUnion(CrossRankUnionWarMatchData battleMatch, CrossRankUnionWarLineData battleLine, String unionId, long nowTime){
        int lineUnion1WinCount = 0;
        int lineUnion2WinCount = 0;
        for(CrossRankUnionWarLineData lineData : battleMatch.getBattleLineMap().values()){
            if(StringUtils.isNullOrEmpty(lineData.getWinUnionId())){

            }else if(battleMatch.getUnionId1().equals(lineData.getWinUnionId())){
                lineUnion1WinCount++;
            }else if(battleMatch.getUnionId2().equals(lineData.getWinUnionId())){
                lineUnion2WinCount++;
            }
        }
        //原本3条线出现胜负就不了，现在要继续了
        /*if(lineUnion1WinCount >= 3 || lineUnion2WinCount >= 3){
            return;
        }*/
        battleLine.setWinUnionId(unionId);
        battleLine.setWinTime(nowTime);
    }

    private boolean checkWaitTime(CrossRankUnionWarMatchData battleMatch,CrossRankUnionWarLineData battleLine,long nowTime){
        if(battleLine.getUnion1StartWaitTime() != 0){
            if(nowTime - battleLine.getUnion1StartWaitTime() + battleLine.getUnion1WaitTime() >= config.getWaitWinTime() * 1000){
                setLineWinUnion(battleMatch,battleLine,battleLine.getUnionId2(),nowTime);
                return true;
            }
        }else{
            if(battleLine.getUnion1WaitTime() >= config.getWaitWinTime() * 1000){
                setLineWinUnion(battleMatch,battleLine,battleLine.getUnionId2(),nowTime);
                return true;
            }
        }
        if(battleLine.getUnion2StartWaitTime() != 0){
            if(nowTime - battleLine.getUnion2StartWaitTime() + battleLine.getUnion2WaitTime() >= config.getWaitWinTime() * 1000){
                setLineWinUnion(battleMatch,battleLine,battleLine.getUnionId1(),nowTime);
                return true;
            }
        }else{
            if(battleLine.getUnion2WaitTime() >= config.getWaitWinTime() * 1000){
                setLineWinUnion(battleMatch,battleLine,battleLine.getUnionId1(),nowTime);
                return true;
            }
        }
        return false;
    }

    //干掉一个加一个
    private void addKillRank(CrossRankUnionWarBattlePatronData unionPatron){
        CrossRankUnionWarMatchData match = getGameNoMatch(unionPatron.getGameNo());
        if(match == null){
            return;
        }
        if(!match.getKillRankMap().containsKey(unionPatron.getUserId())){
            return;
        }
        CrossRankUnionWarKillRankData rankData = match.getKillRankMap().get(unionPatron.getUserId());
        rankData.setKillTimes(rankData.getKillTimes() + 1);
        CrossRankUnionWarUnionData unionData = getUnionData(unionPatron.getUserId());
        if(unionData != null){
            Map<Long, CrossRankUnionWarMemberData> memberDataMap = unionData.getMemberMap();
            CrossRankUnionWarMemberData memberData = memberDataMap.get(unionPatron.getUserId());
            memberData.addKillNum(1);
            addConditionSync(memberData.getUserId(),1,BigInteger.valueOf(memberData.getKillNum()),"");
            unionData.setMemberMap(memberDataMap);
        }
        addNeedUpdateMatch(match);
    }

    private void addConditionSync(long userId,int type,BigInteger value ,String param){
        CrossUserBaseInfo userBaseInfo = CrossUserMgr.getCrossUserBaseInfo(userId);
        if(userBaseInfo != null){
            CrossRankUnionConditionSyncData conditionSyncData = new CrossRankUnionConditionSyncData();
            conditionSyncData.setServerId(userBaseInfo.getUserBaseInfo().getServerId());
            conditionSyncData.setUserId(userBaseInfo.getUserId());
            conditionSyncData.setType(type);
            conditionSyncData.setParam(param);
            conditionSyncData.setValue(value);
            addNeedSyncConditionMap(conditionSyncData);
        }
    }

    private void addGambleConditionAllSync(long userId,int type,BigInteger value ,String param){
        for(long serverId : config.getActivityInfo().getServerIdList()){
            CrossRankUnionConditionSyncData conditionSyncData = new CrossRankUnionConditionSyncData();
            conditionSyncData.setServerId(serverId);
            conditionSyncData.setUserId(-1);
            conditionSyncData.setType(type);
            conditionSyncData.setParam(param);
            conditionSyncData.setValue(value);
            addNeedSyncConditionMap(conditionSyncData);
        }
    }

    private void dealWinPatrons(CrossRankUnionWarBattlePatronData unionPatron,BigInteger bool,long battleTime,String enemyUnionId){
        //每次胜利扣除血量上限debuff
        int debuff = config.getPatronsWinDebuff();
        //胜利达到多少场次就要退场了
        int winMaxTimes = config.getPatronsWinMaxCount();
        BigInteger subBool = bool.multiply(BigInteger.valueOf(debuff)).divide(BigInteger.valueOf(1000));
        BigInteger nowBool = bool.subtract(subBool);
        unionPatron.setBool(nowBool);
        unionPatron.setKillTimes(unionPatron.getKillTimes() + 1);
        if(unionPatron.getKillTimes() >= winMaxTimes){
            setPatronsDie(unionPatron,enemyUnionId,battleTime);
        }
        addNeedUpdateBattlePatrons(unionPatron);
    }


    //拉一个还活着的门客出来,并且算出他什么时候开打
    private CrossRankUnionWarBattlePatronData getAlivePatron(Map<Integer, CrossRankUnionWarBattlePatronData> unionPatronsMap){
        //开始对单次数，理论上是一个人一次，有杀敌的加上杀敌数，有等待时间的还要加上等待时间
        for(int i = 1;i <= unionPatronsMap.size();i++){
            CrossRankUnionWarBattlePatronData unionPatrons = unionPatronsMap.get(i);
            if(!unionPatrons.isDie()){
                return unionPatrons;
            }
        }
        return null;
    }

    private void endTurn(int turn){
        //可以生成下一轮对战数据了就去把竞猜数据结了
        gambleOver(turn);
        clearBattle(turn);
        clearWaitPatrons(turn);
        clearLog(turn);
    }

    //生成对战数据
    public void makeTurnBattle(int turn,Map<Integer,List<String>> unionMap){
        Map<Integer, List<CrossRankUnionWarMatchData>> divisionMatchMap = new ConcurrentHashMap<>();
        for(int divisionId : unionMap.keySet()){
            noticeDivisionCondition(divisionId,unionMap.get(divisionId));
            List<CrossRankUnionWarMatchData> matchList = new ArrayList<>();
            if(!config.isAllRandomDivision(divisionId)){
                matchList = randomMatch4PartVersion2(turn,divisionId,unionMap.get(divisionId));
                divisionMatchMap.put(divisionId,matchList);
            }else{
                matchList = randomMatch(turn,divisionId,unionMap.get(divisionId));
                divisionMatchMap.put(divisionId,matchList);
            }
            if(!divisionTurnMatchMap.containsKey(divisionId)){
                divisionTurnMatchMap.put(divisionId,new ConcurrentHashMap<>());
            }
            divisionTurnMatchMap.get(divisionId).put(turn,matchList);
            //策划优化下一次比赛把上一次比赛的指挥官赋予
            initUnionOpUser(matchList);
        }
        turnDivisionMatchMap.put(turn,divisionMatchMap);
    }
    //新的优化，匹配规则：同赛区内，相同分数的商会将优先两两随机匹配；同分匹配完后，还有剩余的商会，再根据分数就近原则进行匹配
    public void makeTurnBattle2(int turn,Map<Integer,List<String>> unionMap){
        printDebugTime();
        Map<Integer, List<CrossRankUnionWarMatchData>> divisionMatchMap = new ConcurrentHashMap<>();
        for(int divisionId : unionMap.keySet()){
            noticeDivisionCondition(divisionId,unionMap.get(divisionId));
            List<CrossRankUnionWarMatchData> matchList = new ArrayList<>();
            if(turn == config.getLastTimeConfig().getSession()){//又又又优化了，最后一轮用比分匹配
                matchList = randomMatchIntegralVersion4(turn, divisionId, unionMap.get(divisionId));
            }else {
                matchList = randomMatchNVersion4(turn, divisionId, unionMap.get(divisionId));
            }
            divisionMatchMap.put(divisionId,matchList);
            if(!divisionTurnMatchMap.containsKey(divisionId)){
                divisionTurnMatchMap.put(divisionId,new ConcurrentHashMap<>());
            }
            divisionTurnMatchMap.get(divisionId).put(turn,matchList);
            //策划优化下一次比赛把上一次比赛的指挥官赋予
            initUnionOpUser(matchList);
        }
        turnDivisionMatchMap.put(turn,divisionMatchMap);
    }

    //策划优化下一次比赛把上一次比赛的指挥官赋予
    private void initUnionOpUser(List<CrossRankUnionWarMatchData> matchList){
        for(CrossRankUnionWarMatchData matchData : matchList){
            if(!StringUtils.isNullOrEmpty(matchData.getUnionId1())){
                CrossRankUnionWarUnionData unionData = getUnionData(matchData.getUnionId1());
                Map<Integer, Map<Integer, List<Long>>> gameNoOpMap = unionData.getOpUserIdMap();
                Map<Integer, List<Long>> opMap = getOpLastUserIdMap(gameNoOpMap);
                if(opMap != null){
                    if(gameNoOpMap.containsKey(matchData.getGameNo())){
                        Map<Integer, List<Long>> tempOpMap = gameNoOpMap.get(matchData.getGameNo());
                        for(int line : opMap.keySet()){
                            List<Long> opUserList = opMap.get(line);
                            for(long userId : opUserList){
                                CrossRankUnionWarMemberData memberData = getUnionMember(userId);
                                if(memberData != null && memberData.getPosition() != eUnionPosition.Master.getValue() &&  memberData.getPosition() != eUnionPosition.DeputyMaster.getValue()){
                                    logger.info("巅峰活动{},线路{}继承指挥官{}",getActivityId(),line,userId);
                                    tempOpMap.get(line).add(userId);
                                }
                            }
                        }
                    }
                    unionData.setOpUserIdMap(gameNoOpMap);
                }
            }
            if(!StringUtils.isNullOrEmpty(matchData.getUnionId2())){
                CrossRankUnionWarUnionData unionData = getUnionData(matchData.getUnionId2());
                Map<Integer, Map<Integer, List<Long>>> gameNoOpMap = unionData.getOpUserIdMap();
                Map<Integer, List<Long>> opMap = getOpLastUserIdMap(gameNoOpMap);
                if(opMap != null){
                    if(gameNoOpMap.containsKey(matchData.getGameNo())){
                        Map<Integer, List<Long>> tempOpMap = gameNoOpMap.get(matchData.getGameNo());
                        for(int line : opMap.keySet()){
                            List<Long> opUserList = opMap.get(line);
                            for(long userId : opUserList){
                                CrossRankUnionWarMemberData memberData = getUnionMember(userId);
                                if(memberData != null && memberData.getPosition() != eUnionPosition.Master.getValue() &&  memberData.getPosition() != eUnionPosition.DeputyMaster.getValue()){
                                    logger.info("巅峰活动{},线路{}继承指挥官{}",getActivityId(),line,userId);
                                    tempOpMap.get(line).add(userId);
                                }
                            }
                        }
                    }
                    unionData.setOpUserIdMap(gameNoOpMap);
                }
            }
        }
    }

    //获取上一次的指挥官
    private Map<Integer, List<Long>> getOpLastUserIdMap(Map<Integer, Map<Integer, List<Long>>> opMap){
        if(opMap == null){
            return null;
        }
        List<Integer> gameNoList = new ArrayList<>(opMap.keySet());
        Collections.sort(gameNoList);
        Collections.reverse(gameNoList);
        if(gameNoList.size() > 1){
            return opMap.get(gameNoList.get(1));
        }
        return null;
    }

    //竞猜结榜
    private void gambleOver(int turn){
        if(turn > 0){
            CrossRankUnionWarGambleData gambleData = gambleMap.get(turn);
            Map<Integer, List<String>> gambleNoMap = gambleData.getGameNoMap();
            List<String> winUnionIdList = gambleData.getWinUnionIdList();
            for(Integer gameNo : gambleNoMap.keySet()){
                CrossRankUnionWarMatchData matchData = getGameNoMatch(gameNo);
                if(matchData == null){
                    continue;
                }
                winUnionIdList.add(matchData.getWinUnionId());
            }
            gambleData.setWinUnionIdList(winUnionIdList);
            gambleData.setOver(true);
            addNeedUpdateGamble(gambleData);
            Map<Long, Map<Integer, String>> guessMap = gambleData.getGuessUnionIdMap();
            for(long userId : guessMap.keySet()){
                //才对几个
                int rightCount = 0;
                for(String guessUnionId : guessMap.get(userId).values()){
                    if(winUnionIdList.contains(guessUnionId)){
                        rightCount = rightCount+1;
                    }
                }
                addConditionSync(userId,4,BigInteger.valueOf(rightCount),getGamebleRightCountString(turn));
            }
            //发一条更新所有玩家的竞猜人数的
            addGambleConditionAllSync(-1,4,BigInteger.valueOf(-1),getGamebleRightCountString(turn));
        }
    }

    //把才对次数对应分配到该分配的地方
    private void addGamebleRightCount(int turn,int rightCount,long userId){
        CrossRankUnionWarGambleData gambleData = gambleMap.get(turn);
        List<Integer> rightCountList = new ArrayList<>(gambleData.getRightMap().keySet());
        Collections.sort(rightCountList);
        Collections.reverse(rightCountList);
        for(int configRightCount : rightCountList){
            if(rightCount >= configRightCount){
                gambleData.getRightMap().put(configRightCount,gambleData.getRightMap().getOrDefault(configRightCount,0) + 1);
                gambleData.getRightUserMap().get(configRightCount).add(userId);
                break;
            }
        }
    }

    //猜对个数的合集
    private String getGamebleRightCountString(int turn){
        CrossRankUnionWarGambleData gambleData = gambleMap.get(turn);
        if(gambleData.getRightMap().size() == 0){
            synchronized (gambleData.getRightMap()){
                if(gambleData.getRightMap().size() == 0){
                    for(int rightCount : config.getGamebleRightCountList(turn)){
                        gambleData.getRightMap().put(rightCount,0);
                        gambleData.getRightUserMap().put(rightCount,new ArrayList<>());
                    }
                    Map<Long, Map<Integer, String>> guessMap = gambleData.getGuessUnionIdMap();
                    for(Long userId : guessMap.keySet()){
                        //才对几个
                        int rightCount = 0;
                        for(String guessUnionId : guessMap.get(userId).values()){
                            if(gambleData.getWinUnionIdList().contains(guessUnionId)){
                                rightCount = rightCount+1;
                            }
                        }
                        addGamebleRightCount(turn,rightCount,userId);
                    }
                }
                //不保存了。没空保存了
//                addNeedUpdateGamble(gambleData);
            }
        }
        String retStr = turn + "|";
        //轮次|才对次数=人次;才对次数=人次;才对次数=人次;才对次数=人次;才对次数=人次
        for(int rightCount : gambleData.getRightMap().keySet()){
            retStr = retStr + rightCount + "=" + gambleData.getRightMap().get(rightCount) + ";";
        }
        return retStr.substring(0,retStr.length() - 1);
    }

    //晋级到什么赛区了通知游戏服触发
    private void noticeDivisionCondition(int divisionId,List<String> unionList){
        for(String unionId : unionList){
            CrossRankUnionWarUnionData unionData = getUnionData(unionId);
            for(CrossRankUnionWarMemberData memberData : unionData.getMemberMap().values()){
                addConditionSync(memberData.getUserId(),2,BigInteger.valueOf(divisionId),"");
            }
        }
    }

    //比赛生成后生成指挥官数据
    private void initMatchUnionCommander(CrossRankUnionWarMatchData match){
        CrossRankUnionWarUnionData union1Data = getUnionData(match.getUnionId1());
        Map<Integer, Map<Integer,List<Long>>> opMap = union1Data.getOpUserIdMap();
        if(!opMap.containsKey(match.getGameNo())){
            Map<Integer, List<Long>> lineMap = new ConcurrentHashMap<>();
            for(int line = 1;line <= 5; line++){
                lineMap.put(line,new ArrayList<>());
            }
            opMap.put(match.getGameNo(),lineMap);
            union1Data.setOpUserIdMap(opMap);
        }
        if(!StringUtils.isNullOrEmpty(match.getUnionId2())){
            CrossRankUnionWarUnionData union2Data = getUnionData(match.getUnionId2());
            Map<Integer,Map<Integer,List<Long>>> op2Map = union2Data.getOpUserIdMap();
            if(!op2Map.containsKey(match.getGameNo())){
                Map<Integer, List<Long>> lineMap = new ConcurrentHashMap<>();
                for(int line = 1;line <= 5; line++){
                    lineMap.put(line,new ArrayList<>());
                }
                op2Map.put(match.getGameNo(),lineMap);
                union2Data.setOpUserIdMap(op2Map);
            }
        }
    }

    private void initUnionDonateGame(CrossRankUnionWarMatchData match){
        int gameNo = match.getGameNo();
        CrossRankUnionWarUnionData union1Data = getUnionData(match.getUnionId1());
        Map<Integer, Map<Integer, Integer>> donateMap = union1Data.getDonateMap();
        if(!donateMap.containsKey(gameNo)){
            Map<Integer, Integer> tempMap = new ConcurrentHashMap<>();
            for(int i = 1; i <= 5;i++){
                tempMap.put(i,0);
            }
            donateMap.put(gameNo,tempMap);
            union1Data.setDonateMap(donateMap);
        }
        if(!StringUtils.isNullOrEmpty(match.getUnionId2())){
            CrossRankUnionWarUnionData union2Data = getUnionData(match.getUnionId2());
            Map<Integer, Map<Integer, Integer>> donate2Map = union2Data.getDonateMap();
            if(!donate2Map.containsKey(gameNo)){
                Map<Integer, Integer> tempMap = new ConcurrentHashMap<>();
                for(int i = 1; i <= 5;i++){
                    tempMap.put(i,0);
                }
                donate2Map.put(gameNo,tempMap);
                union2Data.setDonateMap(donate2Map);
            }
        }
    }

    //完全随机队伍比赛
    private List<CrossRankUnionWarMatchData> randomMatch(int turn, int divisionId, List<String> unionIdList){
        int no = 1;
        List<CrossRankUnionWarMatchData> matchList = new ArrayList<>();
        List<String> tempUnionIdList = new ArrayList<>(unionIdList);
        while (tempUnionIdList.size() > 0){
            int unionId1Index = randomHelper.next(0,tempUnionIdList.size());
            String unionId1 = tempUnionIdList.get(unionId1Index);
            tempUnionIdList.remove(unionId1);
            String unionId2 = "";
            if(tempUnionIdList.size() != 0){
                int unionId2Index = randomHelper.next(0,tempUnionIdList.size());
                unionId2 = tempUnionIdList.get(unionId2Index);
                tempUnionIdList.remove(unionId2);
            }
            matchList.add(initMatch(turn,divisionId,unionId1,unionId2,no++));
        }
        return matchList;
    }


    //大到小排序
    class UnionEarnSpeedSort implements Comparator<CrossRankUnionWarUnionData> {
        @Override
        public int compare(CrossRankUnionWarUnionData o1, CrossRankUnionWarUnionData o2) {
            if (o1.getUnionBaseInfo().getTotalEarnSpeed().compareTo(o2.getUnionBaseInfo().getTotalEarnSpeed()) == 0) {
                return 0;
            }
            if (o1.getUnionBaseInfo().getTotalEarnSpeed().compareTo(o2.getUnionBaseInfo().getTotalEarnSpeed()) > 0) {
                return -1;
            }
            return 1;
        }
    }
    class WaitPatronEarnSpeedSort implements Comparator<CrossRankUnionWarWaitPatronData> {
        @Override
        public int compare(CrossRankUnionWarWaitPatronData o1, CrossRankUnionWarWaitPatronData o2) {
            if (o1.getEarnSpeed().compareTo(o2.getEarnSpeed()) == 0) {
                return 0;
            }
            if (o1.getEarnSpeed().compareTo(o2.getEarnSpeed()) > 0) {
                return -1;
            }
            return 1;
        }
    }

    //更具策划的规则配对比赛
    //例如：一共256个商会，拆成4部分也就是每个部分是64个商会，将前64名的商会和最后64名的商会进行两两随机匹配，然后65~128名的商会与129~192名的商会进行两两随机匹配，依次类推
    //轮空情况假设：一共取256个商会，当只有250个商会时，则250个商会直接匹配，没有轮空商会出现；若有251个商会出现单数，则会有1个商会出现轮空情况
    //当商会数量不足被4整除时，会补空位置至被4整除位置，按照头尾中间的顺序进行补空，例如商会被分为1234段数据，则按照顺序1423的位置进行补空操作，缺1个空位则补到1段，缺2个空位则补到14段，缺3个空位则补到142段，保证只有1场轮空情况。
    private List<CrossRankUnionWarMatchData> randomMatch4Part(int turn, int divisionId, List<String> unionIdList){
        List<CrossRankUnionWarUnionData> unionEarnSpeedList = new ArrayList<>();
        for(String unionId : unionIdList){
            CrossRankUnionWarUnionData unionData = getUnionData(unionId);
            unionEarnSpeedList.add(unionData);
        }
        unionEarnSpeedList.sort(new UnionEarnSpeedSort());
        //分成四段后每一段多少人
        List<Integer> fourPartList = new ArrayList<>();
        List<List<String>> fourPartUnionIdList = new ArrayList<>();
        int unionCount = unionEarnSpeedList.size();
        //每一段人数
        int yiduan = unionCount/4;
        fourPartList.add(yiduan);
        fourPartList.add(yiduan);
        fourPartList.add(yiduan);
        fourPartList.add(yiduan);
        fourPartUnionIdList.add(new ArrayList<>());
        fourPartUnionIdList.add(new ArrayList<>());
        fourPartUnionIdList.add(new ArrayList<>());
        fourPartUnionIdList.add(new ArrayList<>());
        //是不是整整的一段
        int yushu = unionCount%4;
        if(yushu != 0){
            if(yushu == 1){
                fourPartList.set(0,fourPartList.get(0) + 1);
            }else if(yushu == 2){
                fourPartList.set(0,fourPartList.get(0) + 1);
                fourPartList.set(3,fourPartList.get(3) + 1);
            }else if(yushu == 3){
                fourPartList.set(0,fourPartList.get(0) + 1);
                fourPartList.set(3,fourPartList.get(3) + 1);
                fourPartList.set(1,fourPartList.get(1) + 1);
            }
        }
        int index = 0;
        for(int part = 0; part < fourPartList.size() ; part++){
            int partCount = fourPartList.get(part);
            for(int i = 0;i < partCount;i++){
                fourPartUnionIdList.get(part).add(unionEarnSpeedList.get(index).getUnionId());
                index++;
            }
        }
        List<CrossRankUnionWarMatchData> matchList = new ArrayList<>();
        int no = 1;
        while (fourPartUnionIdList.get(0).size() > 0 || fourPartUnionIdList.get(1).size() > 0){
            if(no > 1000)break;
            int listIndex = randomHelper.next(0,2);
            if(fourPartUnionIdList.get(listIndex).size() == 0){
                listIndex = (listIndex == 0)?1:0;
            }
            int listIndex2 = (listIndex == 0?3:2);
            if(fourPartUnionIdList.get(listIndex).size() > 0){
                int unionId1Index = randomHelper.next(0,fourPartUnionIdList.get(listIndex).size());
                String unionId1 = fourPartUnionIdList.get(listIndex).get(unionId1Index);
                fourPartUnionIdList.get(listIndex).remove(unionId1);
                String unionId2 = "";
                if(fourPartUnionIdList.get(listIndex2).size() != 0){
                    int unionId2Index = randomHelper.next(0,fourPartUnionIdList.get(listIndex2).size());
                    unionId2 = fourPartUnionIdList.get(listIndex2).get(unionId2Index);
                    fourPartUnionIdList.get(listIndex2).remove(unionId2);
                }
                //策划说现在都是第一个商会赚速比较高
                if(!StringUtils.isNullOrEmpty(unionId2) && randomHelper.next(0,2) == 1){
                    matchList.add(initMatch(turn,divisionId,unionId2,unionId1,no++));
                }else{
                    matchList.add(initMatch(turn,divisionId,unionId1,unionId2,no++));
                }
            }
        }
        /*while (fourPartUnionIdList.get(0).size() > 0){
            int unionId1Index = randomHelper.next(0,fourPartUnionIdList.get(0).size());
            String unionId1 = fourPartUnionIdList.get(0).get(unionId1Index);
            fourPartUnionIdList.get(0).remove(unionId1);
            String unionId2 = "";
            if(fourPartUnionIdList.get(3).size() != 0){
                int unionId2Index = randomHelper.next(0,fourPartUnionIdList.get(3).size());
                unionId2 = fourPartUnionIdList.get(3).get(unionId2Index);
                fourPartUnionIdList.get(3).remove(unionId2);
            }
            matchList.add(initMatch(turn,divisionId,unionId1,unionId2,no++));
        }
        while (fourPartUnionIdList.get(1).size() > 0){
            int unionId1Index = randomHelper.next(0,fourPartUnionIdList.get(1).size());
            String unionId1 = fourPartUnionIdList.get(1).get(unionId1Index);
            fourPartUnionIdList.get(1).remove(unionId1);
            String unionId2 = "";
            if(fourPartUnionIdList.get(2).size() != 0){
                int unionId2Index = randomHelper.next(0,fourPartUnionIdList.get(2).size());
                unionId2 = fourPartUnionIdList.get(2).get(unionId2Index);
                fourPartUnionIdList.get(2).remove(unionId2);
            }
            matchList.add(initMatch(turn,divisionId,unionId1,unionId2,no++));
        }*/
        return matchList;
    }

    private List<CrossRankUnionWarMatchData> randomMatch4PartVersion2(int turn, int divisionId, List<String> unionIdList){
        int bigBossNum = config.getBigBossNum();
        List<CrossRankUnionWarMatchData> matchList = new ArrayList<>();
        List<CrossRankUnionWarUnionData> unionEarnSpeedList = new ArrayList<>();
        for(String unionId : unionIdList){
            CrossRankUnionWarUnionData unionData = getUnionData(unionId);
            unionEarnSpeedList.add(unionData);
        }
        unionEarnSpeedList.sort(new UnionEarnSpeedSort());
        List<String> bigBossUnionIdList = new ArrayList<>();
        List<String> notBigBossUnionIdList = new ArrayList<>();
        for(int i = 0; i < unionEarnSpeedList.size(); i++){
            if(i < bigBossNum){
                bigBossUnionIdList.add(unionEarnSpeedList.get(i).getUnionId());
            }else{
                notBigBossUnionIdList.add(unionEarnSpeedList.get(i).getUnionId());
            }
        }
        List<List<String>> matchListList = new ArrayList<>();
        int no = 1;
        while (bigBossUnionIdList.size() > 0 || notBigBossUnionIdList.size() > 0){
            String union1Id = "";
            String union2Id = "";
            if(bigBossUnionIdList.size() > 0){
                union1Id = bigBossUnionIdList.get(0);
                bigBossUnionIdList.remove(union1Id);
                if(notBigBossUnionIdList.size() > 0){
                    union2Id = notBigBossUnionIdList.get(randomHelper.next(0,notBigBossUnionIdList.size()));
                    notBigBossUnionIdList.remove(union2Id);
                }else if(bigBossUnionIdList.size() > 0){
                    union2Id = bigBossUnionIdList.get(randomHelper.next(0,bigBossUnionIdList.size()));
                    bigBossUnionIdList.remove(union2Id);
                }
            }else{
                union1Id = notBigBossUnionIdList.get(0);
                notBigBossUnionIdList.remove(union1Id);
                if(notBigBossUnionIdList.size() > 0){
                    union2Id = notBigBossUnionIdList.get(randomHelper.next(0,notBigBossUnionIdList.size()));
                    notBigBossUnionIdList.remove(union2Id);
                }
            }
            List<String> matchUnionIdList = new ArrayList<>();
            if(!StringUtils.isNullOrEmpty(union2Id) && randomHelper.next(0,2) == 1){
                matchUnionIdList.add(union2Id);
                matchUnionIdList.add(union1Id);
//                matchList.add(initMatch(turn,divisionId,union2Id,union1Id,no++));
            }else{
                matchUnionIdList.add(union1Id);
                matchUnionIdList.add(union2Id);
//                matchList.add(initMatch(turn,divisionId,union1Id,union2Id,no++));
            }
            matchListList.add(matchUnionIdList);
        }
        while (matchListList.size() > 0){
            int index = randomHelper.next(0,matchListList.size());
            List<String> matchUnionIdList = matchListList.get(index);
            matchListList.remove(index);
            matchList.add(initMatch(turn,divisionId,matchUnionIdList.get(0),matchUnionIdList.get(1),no++));
        }
        return matchList;
    }

    //又优化了 匹配规则：同赛区内，相同分数的商会将优先两两随机匹配；同分匹配完后，还有剩余的商会，再根据分数就近原则进行匹配
    private List<CrossRankUnionWarMatchData> randomMatchIntegralVersion3(int turn, int divisionId, List<String> unionIdList){
        List<CrossRankUnionWarMatchData> matchList = new ArrayList<>();
        Map<Integer,String> scoreUnionIdMap = new ConcurrentHashMap<>();
        //一对一对的
        List<List<String>> matchListList = new ArrayList<>();
        for(String unionId : unionIdList){
            CrossRankUnionWarUnionData unionData = getUnionData(unionId);
            if(unionData != null){
                if(scoreUnionIdMap.containsKey(unionData.getScore())){
                    String union1Id = scoreUnionIdMap.get(unionData.getScore());
                    String union2Id = unionId;
                    List<String> matchUnionIdList = new ArrayList<>();
                    matchUnionIdList.add(union1Id);
                    matchUnionIdList.add(union2Id);
                    matchListList.add(matchUnionIdList);
                    scoreUnionIdMap.remove(unionData.getScore());
                }else{
                    scoreUnionIdMap.put(unionData.getScore(),unionId);
                }
            }
        }
        //相近的匹配，那就从大匹配到小吧
        while (scoreUnionIdMap.size() > 0){
            List<Integer> scoreList = new ArrayList<>(scoreUnionIdMap.keySet());
            Collections.sort(scoreList);
            Collections.reverse(scoreList);
            String union1Id = scoreUnionIdMap.get(scoreList.get(0));
            scoreUnionIdMap.remove(scoreList.get(0));
            scoreList.remove(0);
            String union2Id = "";
            if(scoreList.size() > 0){
                union2Id = scoreUnionIdMap.get(scoreList.get(0));
                scoreUnionIdMap.remove(scoreList.get(0));
                scoreList.remove(0);
            }
            List<String> matchUnionIdList = new ArrayList<>();
            matchUnionIdList.add(union1Id);
            matchUnionIdList.add(union2Id);
            matchListList.add(matchUnionIdList);
        }
        int no = 1;
        while (matchListList.size() > 0){
            int index = randomHelper.next(0,matchListList.size());
            List<String> matchUnionIdList = matchListList.get(index);
            matchListList.remove(index);
            matchList.add(initMatch(turn,divisionId,matchUnionIdList.get(0),matchUnionIdList.get(1),no++));
        }
        return matchList;
    }

    /**
     * 匹配规则：按照排名顺序进行匹配，例如第一名打第二名，第三名打第四名
     * @param turn
     * @param divisionId
     * @param unionIdList
     * @return
     */
    private List<CrossRankUnionWarMatchData> randomMatchIntegralVersion4(int turn, int divisionId, List<String> unionIdList) {
        List<CrossRankUnionWarMatchData> matchList = new ArrayList<>();
        //根据分数排序商会
        List<CrossRankUnionWarUnionData> unionList = new ArrayList<>();
        for(String unionId : unionIdList){
            //商会数据
            CrossRankUnionWarUnionData unionData = getUnionData(unionId);
            if(unionData != null) {
                unionList.add(unionData);
            }
        }
        if (unionList.isEmpty()) {
            return matchList;
        }
        //根据score降序排序
        unionList.sort(Comparator.comparingInt(CrossRankUnionWarUnionData::getScore).reversed());
        //两两分为一组,切割数组
        List<List<CrossRankUnionWarUnionData>> unionSpList = ListHelper.partitionList(unionList, 2);//这个2决定了两两分一组
        //创建match
        int no = 1;
        for (List<CrossRankUnionWarUnionData> item : unionSpList) {
            String unionId1 = item.size() <= 0 ? "" : item.get(0).getUnionId();
            String unionId2 = item.size() <= 1 ? "" : item.get(1).getUnionId();
            //init match
            if (!Objects.equals(unionId1, "")) {
                CrossRankUnionWarMatchData matchData = initMatch(turn, divisionId, unionId1, unionId2, no++);
                matchList.add(matchData);
            }
        }
        return matchList;
    }

    //又优化了 匹配规则：新增一个间隔轮数配置，相同的比赛在间隔轮数≤n时，不会出现相同的比赛
    //例如：假设n=2，若A、B商会在第1轮比赛匹配对战了，在接下来的2轮内，将不会再互相遇到，只有在第4轮的时候，才有可能会遇到。
    //其他的随机
    private List<CrossRankUnionWarMatchData> randomMatchNVersion4(int turn, int divisionId, List<String> unionIdList){
        //历史已经匹配过谁了
        Map<String,List<String>> whoWithWho = new ConcurrentHashMap<>();
        int noSameTurn = config.getBattleNoSameTurn();
        for(int i = noSameTurn;i > 0;i--){
            if(turnDivisionMatchMap.containsKey(turn - noSameTurn)){
                for(List<CrossRankUnionWarMatchData> matchDataList : turnDivisionMatchMap.get(turn - noSameTurn).values()){
                    for(CrossRankUnionWarMatchData matchData : matchDataList){
                        if(!StringUtils.isNullOrEmpty(matchData.getUnionId2())){
                            if(unionIdList.contains(matchData.getUnionId1()) && unionIdList.contains(matchData.getUnionId2())){
                                if(!whoWithWho.containsKey(matchData.getUnionId1())){
                                    whoWithWho.put(matchData.getUnionId1(),new ArrayList<>());
                                }
                                if(!whoWithWho.containsKey(matchData.getUnionId2())){
                                    whoWithWho.put(matchData.getUnionId2(),new ArrayList<>());
                                }
                                if(!whoWithWho.get(matchData.getUnionId1()).contains(matchData.getUnionId2())){
                                    whoWithWho.get(matchData.getUnionId1()).add(matchData.getUnionId2());
                                }
                                if(!whoWithWho.get(matchData.getUnionId2()).contains(matchData.getUnionId1())){
                                    whoWithWho.get(matchData.getUnionId2()).add(matchData.getUnionId1());
                                }
                            }
                        }
                    }
                }
            }
        }
        List<List<String>> matchListList = new ArrayList<>();
        List<CrossRankUnionWarMatchData> matchList = new ArrayList<>();
        List<String> goUnionIdList = new ArrayList<>(unionIdList);
        //优先把不能匹配的人匹配了
        while (whoWithWho.size() > 0 || goUnionIdList.size() > 0){
            //不能匹配的最多的商会先匹配
            int unionNoCount = 0;
            String unionId1 = "";
            for(String unionId : whoWithWho.keySet()){
                if(whoWithWho.get(unionId).size() > unionNoCount){
                    unionId1 = unionId;
                    unionNoCount = whoWithWho.get(unionId).size();
                }
            }
            if(StringUtils.isNullOrEmpty(unionId1)){
                unionId1 = goUnionIdList.get(0);
            }
            List<String> tempUnionIdList = new ArrayList<>(goUnionIdList);
            tempUnionIdList.remove(unionId1);
            if(whoWithWho.containsKey(unionId1)){
                tempUnionIdList.removeAll(whoWithWho.get(unionId1));
            }
            if(tempUnionIdList.size() == 0){
                tempUnionIdList = new ArrayList<>(goUnionIdList);
                tempUnionIdList.remove(unionId1);
                if(tempUnionIdList.size() != 0){
                    logger.error("巅峰{},出现了移除掉不能打的商会变成没商会了{}。。。。",getActivityId(),unionId1);
                }
            }
            String unionId2 = "";
            if(tempUnionIdList.size() != 0){
                int index = randomHelper.next(0,tempUnionIdList.size());
                unionId2 = tempUnionIdList.get(index);
            }
            if(unionId1.equals(unionId2)){
                logger.error("巅峰{},比赛自己打自己{}",getActivityId(),unionId1);
            }
            List<String> matchUnionIdList = new ArrayList<>();
            matchUnionIdList.add(unionId1);
            matchUnionIdList.add(unionId2);
            whoWithWho.remove(unionId1);
            whoWithWho.remove(unionId2);
            goUnionIdList.remove(unionId1);
            goUnionIdList.remove(unionId2);
            matchListList.add(matchUnionIdList);
        }
        int no = 1;
        while (matchListList.size() > 0){
            int index = randomHelper.next(0,matchListList.size());
            List<String> matchUnionIdList = matchListList.get(index);
            matchListList.remove(index);
            matchList.add(initMatch(turn,divisionId,matchUnionIdList.get(0),matchUnionIdList.get(1),no++));
        }
        return matchList;
    }

    private CrossRankUnionWarMatchData initMatch(int turn,int divisionId,String unionId1,String unionId2,int no){
        CrossRankUnionWarMatchData matchData = new CrossRankUnionWarMatchData();
        matchData.setActivityId(getActivityId());
        matchData.setGameNo(makeGameNo.getAndIncrement());
        matchData.setTurn(turn);
        matchData.setDivision(divisionId);
        matchData.setUnionId1(unionId1);
        matchData.setUnionId2(unionId2);
        matchData.setStatus(0);
        matchData.setNo(no);
        initMatchWaitPatrons(matchData);
        battlingMatchMap.put(matchData.getGameNo(),matchData);
        battleMatchMap.put(matchData.getGameNo(),matchData);
        Map<Integer, CrossRankUnionWarLineData> battleLineMap = new ConcurrentHashMap<>();
        for(int line = 1;line <= 5;line++){
            CrossRankUnionWarLineData lineData = new CrossRankUnionWarLineData();
            lineData.setActivityId(matchData.getActivityId());
            lineData.setGameNo(matchData.getGameNo());
            lineData.setLine(line);
            lineData.setUnionId1(unionId1);
            lineData.setUnionId2(unionId2);
            lineData.setLineIndex1(new AtomicInteger(1));
            lineData.setLineIndex2(new AtomicInteger(1));
            battleLineMap.put(line,lineData);
            lineData.getBattlePatronsMap().put(unionId1,new ConcurrentHashMap<>());
            lineData.getBattlePatronsMap().put(unionId2,new ConcurrentHashMap<>());
            addNeedInsertLine(lineData);
        }
        matchData.setBattleLineMap(battleLineMap);
        //策划说要每边默认加一个人，不然出现0的数据不好看
        matchData.addUnion1Support();
        matchData.addUnion2Support();
        initMatchUnionCommander(matchData);
        initUnionDonateGame(matchData);
        addNeedInsertMatch(matchData);
        return matchData;
    }

    //初始化门客
    private void initMatchWaitPatrons(CrossRankUnionWarMatchData matchData){
        Map<Long,CrossRankUnionWarKillRankData> killRankMap = new ConcurrentHashMap<>();
        Map<Long,Map<Integer,CrossRankUnionWarWaitPatronData>> initWaitPatronsMap = new ConcurrentHashMap<>();
        if(!StringUtils.isNullOrEmpty(matchData.getUnionId1())){
            CrossRankUnionWarUnionData unionData = unionDataMap.get(matchData.getUnionId1());
            Map<Long, CrossRankUnionWarMemberData> memberDataMap = unionData.getMemberMap();
            for(CrossRankUnionWarMemberData memberData : memberDataMap.values()){
                //退出商会了退出比赛了的不把他的门客加进去
                if(memberData.isQuit())continue;
                Map<Integer, CrossRankUnionWarPatronData> patronDataMap = memberData.getPatronDataMap(matchData.getTurn());
                Map<Integer,CrossRankUnionWarWaitPatronData> tempBattlePatronsMap = new ConcurrentHashMap<>();
                for(CrossRankUnionWarPatronData patronData : patronDataMap.values()){
                    CrossRankUnionWarWaitPatronData waitPatronData = initWaitPatrons(matchData.getGameNo(),memberData.getUserId(),patronData);
                    tempBattlePatronsMap.put(waitPatronData.getPatronId(),waitPatronData);
                    addNeedInsertWaitPatrons(waitPatronData);
                }
                initWaitPatronsMap.put(memberData.getUserId(),tempBattlePatronsMap);
                CrossRankUnionWarKillRankData rankData = new CrossRankUnionWarKillRankData();
                rankData.setUserId(memberData.getUserId());
                rankData.setUpdateTime(System.currentTimeMillis());
                killRankMap.put(memberData.getUserId(),rankData);
            }
        }

        if(!StringUtils.isNullOrEmpty(matchData.getUnionId2())){
            CrossRankUnionWarUnionData unionData = unionDataMap.get(matchData.getUnionId2());
            Map<Long, CrossRankUnionWarMemberData> memberDataMap = unionData.getMemberMap();
            for(CrossRankUnionWarMemberData memberData : memberDataMap.values()){
                Map<Integer, CrossRankUnionWarPatronData> patronDataMap = memberData.getPatronDataMap(matchData.getTurn());
                Map<Integer,CrossRankUnionWarWaitPatronData> tempBattlePatronsMap = new ConcurrentHashMap<>();
                for(CrossRankUnionWarPatronData patronData : patronDataMap.values()){
                    CrossRankUnionWarWaitPatronData waitPatronData = initWaitPatrons(matchData.getGameNo(),memberData.getUserId(),patronData);
                    tempBattlePatronsMap.put(waitPatronData.getPatronId(),waitPatronData);
                    addNeedInsertWaitPatrons(waitPatronData);
                }
                initWaitPatronsMap.put(memberData.getUserId(),tempBattlePatronsMap);

                CrossRankUnionWarKillRankData rankData = new CrossRankUnionWarKillRankData();
                rankData.setUserId(memberData.getUserId());
                rankData.setUpdateTime(System.currentTimeMillis());
                killRankMap.put(memberData.getUserId(),rankData);
            }
        }
        matchData.setWaitPatronsMap(initWaitPatronsMap);
        matchData.setKillRankMap(killRankMap);
        sortLineSendPatrons(matchData);
    }

    //加入商会后把门客加进去
    private void addJoinUnionMatchWaitPatrons(CrossRankUnionWarMatchData matchData, CrossRankUnionWarMemberData memberData){
        Map<Long,Map<Integer,CrossRankUnionWarWaitPatronData>> waitPatronsMap = matchData.getWaitPatronsMap();
        if(waitPatronsMap.containsKey(memberData.getUserId())){
            return;
        }
        Map<Integer, CrossRankUnionWarPatronData> patronDataMap = memberData.getPatronDataMap(matchData.getTurn());
        Map<Integer,CrossRankUnionWarWaitPatronData> tempBattlePatronsMap = new ConcurrentHashMap<>();
        for(CrossRankUnionWarPatronData patronData : patronDataMap.values()){
            CrossRankUnionWarWaitPatronData waitPatronData = initWaitPatrons(matchData.getGameNo(),memberData.getUserId(),patronData);
            tempBattlePatronsMap.put(waitPatronData.getPatronId(),waitPatronData);
            addNeedInsertWaitPatrons(waitPatronData);
        }
        waitPatronsMap.put(memberData.getUserId(),tempBattlePatronsMap);
        matchData.setWaitPatronsMap(waitPatronsMap);

        //击杀榜单
        Map<Long,CrossRankUnionWarKillRankData> killRankMap = matchData.getKillRankMap();
        CrossRankUnionWarKillRankData rankData = new CrossRankUnionWarKillRankData();
        rankData.setUserId(memberData.getUserId());
        rankData.setUpdateTime(System.currentTimeMillis());
        killRankMap.put(memberData.getUserId(),rankData);
        matchData.setKillRankMap(killRankMap);
        addNeedUpdateMatch(matchData);
    }

    private void removeQuitUnionMatchWaitPatrons(CrossRankUnionWarMatchData matchData, CrossRankUnionWarMemberData memberData){
        Map<Long,Map<Integer,CrossRankUnionWarWaitPatronData>> waitPatronsMap = matchData.getWaitPatronsMap();
        for(CrossRankUnionWarWaitPatronData waitPatronData : waitPatronsMap.get(memberData.getUserId()).values()){
            addNeedDelWaitPatrons(waitPatronData);
        }
        //门客列表
        waitPatronsMap.remove(memberData.getUserId());
        matchData.setWaitPatronsMap(waitPatronsMap);

        //击杀榜单
        Map<Long,CrossRankUnionWarKillRankData> killRankMap = matchData.getKillRankMap();
        killRankMap.remove(memberData.getUserId());
        matchData.setKillRankMap(killRankMap);

        CrossRankUnionWarUnionData unionData = getUnionData(memberData.getUserId());
        if(unionData != null){
            Map<Integer, Map<Integer, List<Long>>> opMap = unionData.getOpUserIdMap();
            //清除掉指挥官
            for(Map<Integer, List<Long>> lineMap : opMap.values()){
                for(List<Long> opUserIdMap : lineMap.values()){
                    opUserIdMap.remove(memberData.getUserId());
                }
            }
            unionData.setOpUserIdMap(opMap);
        }
        addNeedUpdateMatch(matchData);
    }

    /**
     * 初始化一个战斗门客
     * @param lineIndex
     * @param patronData
     * @param dieTime 上一个门客什么时候死的，就是下一个门客的上场时间sendTime
     * @return
     */
    private CrossRankUnionWarBattlePatronData initBattlePatrons(int lineIndex,CrossRankUnionWarWaitPatronData patronData,long dieTime){
        CrossRankUnionWarBattlePatronData battlePatronData = new CrossRankUnionWarBattlePatronData();
        battlePatronData.setActivityId(patronData.getActivityId());
        battlePatronData.setUserId(patronData.getUserId());
        battlePatronData.setGameNo(patronData.getGameNo());
        if(patronData.getPatronId() == 0){
            logger.error("巅峰{}设置门客id为0，gameNo:{},userId:{},line:{},lineIndex:{}",getActivityId(),patronData.getGameNo(),patronData.getUserId(),patronData.getLine(),patronData.getLineIndex());
        }
        battlePatronData.setPatronId(patronData.getPatronId());
        battlePatronData.setLine(patronData.getLine());
        battlePatronData.setLineIndex(lineIndex);
        battlePatronData.setPatronsNo(makePatronsNo.getAndIncrement());
        battlePatronData.setEarnSpeed(patronData.getEarnSpeed());
        battlePatronData.setBool(patronData.getEarnSpeed());
        battlePatronData.setSkinId(patronData.getSkinId());
        battlePatronData.setPromotionId(patronData.getPatronId());
        battlePatronData.setSendTime(dieTime);
        return battlePatronData;
    }

    private CrossRankUnionWarWaitPatronData initWaitPatrons(int gameNo,long userId,CrossRankUnionWarPatronData patronData){
        CrossRankUnionWarWaitPatronData battlePatronData = new CrossRankUnionWarWaitPatronData();
        battlePatronData.setActivityId(getActivityId());
        battlePatronData.setUserId(userId);
        battlePatronData.setGameNo(gameNo);
        battlePatronData.setPatronId(patronData.getPatronsId());
        battlePatronData.setEarnSpeed(patronData.getEarnSpeed());
        battlePatronData.setSkinId(patronData.getSkinId());
        battlePatronData.setPromotionId(patronData.getPatronsId());
        return battlePatronData;
    }


    //去本服拉取所有门客的信息
    public void sendServerGetPatrons(int turn,boolean isAll){
        Map<Long,List<Integer>> userPatronsIdMap = new ConcurrentHashMap<>();
        Map<Long,List<Long>> serverUserIdMap = new ConcurrentHashMap<>();
        for(CrossRankUnionWarUnionData unionData : unionDataMap.values()){
            if(!isAll && unionData.isDie())continue;
            for(CrossRankUnionWarMemberData memberData : unionData.getMemberMap().values()){
                if(!isAll){
                    if(memberData.getPatronDataMap(turn) != null){
                        List<Integer> patronsIdList = new ArrayList<>(memberData.getPatronDataMap(turn).keySet());
                        userPatronsIdMap.put(memberData.getUserId(),patronsIdList);
                    }
                }
                if(!serverUserIdMap.containsKey(memberData.getServerId())){
                    serverUserIdMap.put(memberData.getServerId(),new ArrayList<>());
                }
                serverUserIdMap.get(memberData.getServerId()).add(memberData.getUserId());
            }
        }
        if(serverUserIdMap.size() > 0){
            for(long serverId : serverUserIdMap.keySet()){
                RankUnionWarProto.CrossRankUnionWarGetPatronsReqMsg.Builder reqMsg = RankUnionWarProto.CrossRankUnionWarGetPatronsReqMsg.newBuilder();
                reqMsg.setActivityId(getActivityId());
                reqMsg.setTurn(turn);
                int sendIndex = 0;
                for(long userId : serverUserIdMap.get(serverId)){
                    RankUnionWarProto.CrossRankUnionWarGetPatronsInfoMsg.Builder getInfoMsg = RankUnionWarProto.CrossRankUnionWarGetPatronsInfoMsg.newBuilder();
                    getInfoMsg.setUserId(userId);
                    getInfoMsg.setUnionId(getUnionData(userId).getUnionId());
                    if(userPatronsIdMap.containsKey(userId)){
                        getInfoMsg.addAllPatronsId(userPatronsIdMap.get(userId));
                    }
                    reqMsg.addInfos(getInfoMsg);
                    sendIndex++;
                    //一百个人一百个人拉
                    if(sendIndex >= 1000){
                        RankUnionWarProto.CrossRankUnionWarGetPatronsReqMsg.Builder tempReqMsg = reqMsg;
                        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_CROSS_GET_PATRONS, tempReqMsg);
                        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, 0, pbMsg);
                        sendIndex = 0;
                        reqMsg = RankUnionWarProto.CrossRankUnionWarGetPatronsReqMsg.newBuilder();
                        reqMsg.setActivityId(getActivityId());
                        reqMsg.setTurn(turn);
                    }
                }
                if(reqMsg.getInfosList().size() > 0){
                    YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_CROSS_GET_PATRONS, reqMsg);
                    CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, 0, pbMsg);
                }
            }
        }
    }

    /**
     * 拉取对应商会的门客更新
     * @param unionData
     */
    public void sendGetAllPatrons(CrossRankUnionWarUnionData unionData,int turn){
        Map<Long,List<Long>> serverUserIdMap = new ConcurrentHashMap<>();
        for(CrossRankUnionWarMemberData memberData : unionData.getMemberMap().values()){
            if(!serverUserIdMap.containsKey(memberData.getServerId())){
                serverUserIdMap.put(memberData.getServerId(),new ArrayList<>());
            }
            serverUserIdMap.get(memberData.getServerId()).add(memberData.getUserId());
        }
        if(serverUserIdMap.size() > 0){
            for(long serverId : serverUserIdMap.keySet()){
                RankUnionWarProto.CrossRankUnionWarGetPatronsReqMsg.Builder reqMsg = RankUnionWarProto.CrossRankUnionWarGetPatronsReqMsg.newBuilder();
                reqMsg.setActivityId(getActivityId());
                reqMsg.setTurn(turn);
                //包太大了，不能一下全发
                int sendIndex = 0;
                for(long userId : serverUserIdMap.get(serverId)){
                    RankUnionWarProto.CrossRankUnionWarGetPatronsInfoMsg.Builder getInfoMsg = RankUnionWarProto.CrossRankUnionWarGetPatronsInfoMsg.newBuilder();
                    getInfoMsg.setUserId(userId);
                    getInfoMsg.setUnionId(unionData.getUnionId());
                    reqMsg.addInfos(getInfoMsg);
                    sendIndex++;
                    if(sendIndex >= 1000){
                        RankUnionWarProto.CrossRankUnionWarGetPatronsReqMsg.Builder tempReqMsg = reqMsg;
                        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_CROSS_GET_PATRONS, tempReqMsg);
                        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, 0, pbMsg);
                        sendIndex = 0;
                        reqMsg = RankUnionWarProto.CrossRankUnionWarGetPatronsReqMsg.newBuilder();
                        reqMsg.setActivityId(getActivityId());
                        reqMsg.setTurn(turn);
                    }
                }
                if(reqMsg.getInfosList().size() > 0){
                    YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_CROSS_GET_PATRONS, reqMsg);
                    CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, 0, pbMsg);
                }
            }
        }
    }

    public void logicMain(){
        long nowTime = System.currentTimeMillis();
        if(nowTime - lastUpdatePatronsTime > DateHelper.SECOND_MILLIONS * 20){
            unionSteamGetTask();
            makeTurnBattle2();
            lastUpdatePatronsTime = nowTime;
        }
        updatePatrons();
        matchProcess();
        syncBattlePatronsCount();
        syncBattleWin();
        syncBattleNotice();
        syncCondition();
        syncBarrage();
    }

    private long lastUpdatePatronsTime = 0;

    private void updatePatrons(){
        //区服主动发上来
        /*if(crossRankUnionWarData.getGameTurn() == 0)return;
        long nowTime = System.currentTimeMillis();
        RankUnionWarTimeConfig timeConfig = config.getTimeConfig(nowTime);
        //前面备战期1分钟更新一次门客数据
        if(nowTime < timeConfig.getStartTime() - DateHelper.SECOND_MILLIONS * 20){
            if(nowTime - lastUpdatePatronsTime > DateHelper.SECOND_MILLIONS * 20){
                sendServerGetPatrons(crossRankUnionWarData.getGameTurn(),true);
                lastUpdatePatronsTime = nowTime;
            }
            //最后比赛快开始20秒钟每3秒更新一次门客数据
        }else if(nowTime > timeConfig.getStartTime() - DateHelper.SECOND_MILLIONS * 20 && nowTime < timeConfig.getStartTime()){
            if(nowTime - lastUpdatePatronsTime > DateHelper.SECOND_MILLIONS * 3){
                sendServerGetPatrons(crossRankUnionWarData.getGameTurn(),true);
                lastUpdatePatronsTime = nowTime;
            }
        }*/
    }

    //去拉队伍来比赛
    private void unionSteamGetTask(){
        if(!crossRankUnionWarData.isUnionGet()){
            long nowTime = System.currentTimeMillis();
            RankUnionWarTimeConfig zeroConfig = config.getTimeConfig(0);
            if(zeroConfig == null){
                //比赛开始提前十秒钟就去拉商会
                if(nowTime > config.getActivityInfo().getBeginTime() * 1000 - DateHelper.SECOND_MILLIONS * 25){
                    sendGetUnionMsg();
                }
            }else{
                //多了个报名期
                if(nowTime > config.getActivityInfo().getBeginTime() * 1000 + zeroConfig.getDurTime() * DateHelper.MINUTE_MILLIONS
                        - DateHelper.SECOND_MILLIONS * 25){
                    sendGetUnionMsg();
                }
            }
        }
    }

    public void sendGetUnionMsg() {
        logger.error("巅峰商会{}还没有拉到活动数据，去跨服商会拉取",getActivityId());
        RankUnionWarProto.CrossRankUnionWarGetMatchUnionReqMsg.Builder builder = RankUnionWarProto.CrossRankUnionWarGetMatchUnionReqMsg.newBuilder();
        builder.setActivityId(getActivityId());
        List<Long> serverIdList = config.getActivityInfo().getServerIdList();
        builder.setEarnSpeedTopCount(config.getUnionCount());
        builder.addAllServerId(serverIdList);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverIdList.get(randomHelper.next(0,serverIdList.size())), 0, YanQuMessageUtils.buildMessage(CrossProtocol.C3_CROSS_RANKUNIONWAR_GET_UNION_REQ, builder));
    }

    public void sendUpdateUnionMsg() {
        logger.error("巅峰{}发送更新商会信息消息activityId:{}",getActivityId(),getActivityId());
        RankUnionWarProto.CrossRankUnionWarGetMatchUnionReqMsg.Builder builder = RankUnionWarProto.CrossRankUnionWarGetMatchUnionReqMsg.newBuilder();
        builder.setActivityId(getActivityId());
        List<Long> serverIdList = config.getActivityInfo().getServerIdList();
        builder.setEarnSpeedTopCount(config.getUnionCount());
        builder.addAllServerId(serverIdList);
        Map<String, CrossRankUnionWarUnionData> tempUnionDataMap = new ConcurrentHashMap<>(unionDataMap);
        for(CrossRankUnionWarUnionData unionData : tempUnionDataMap.values()){
            builder.addUnionId(unionData.getUnionId());
        }
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverIdList.get(randomHelper.next(0,serverIdList.size())), 0, YanQuMessageUtils.buildMessage(CrossProtocol.C3_CROSS_RANKUNIONWAR_GET_UNION_REQ, builder));
    }


    //比赛详情
    public void matchDetailList(long serverId,long userId) {
        RankUnionWarProto.RankUnionWarMatchDetailListRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarMatchDetailListRespMsg.newBuilder();
        respMsg.setRet(0);
        for(int turn : turnDivisionMatchMap.keySet()){
            RankUnionWarProto.RankUnionWarMatchDetailTurnMsg.Builder turnMsg = RankUnionWarProto.RankUnionWarMatchDetailTurnMsg.newBuilder();
            turnMsg.setTurn(turn);
            Map<Integer, List<CrossRankUnionWarMatchData>> divisionMatchMap = turnDivisionMatchMap.get(turn);
            for(Integer divisionId : divisionMatchMap.keySet()){
                List<CrossRankUnionWarMatchData> matchList = divisionMatchMap.get(divisionId);
                for(CrossRankUnionWarMatchData matchData : matchList){
                    turnMsg.addMatches(parseMatchDetailMsg(matchData,userId));
                }
            }
            respMsg.addTurns(turnMsg);
        }
        respMsg.setRank(-1);
        respMsg.setValue("0");
        CrossRankUnionWarUnionData unionData = getUnionData(userId);
        if(unionData != null){
            CrossGeneralActivityUnionRankModel rankListModel = CrossGeneralActivityRankMgr.getCrossActivityUnionRankListModel(getActivityId(), eGamePlayerEventType.RankUnionWarUnionScoreRank.getValue());
            if (null != rankListModel) {
                respMsg.setRank(rankListModel.getMyRank(unionData.getUnionBaseInfo().getServerId(),unionData.getUnionId()));
                for (CrossActivityUnionRank rank : rankListModel.getRankList()) {
                    if (rank.getUnionUid().equals(unionData.getUnionId())) {
                        respMsg.setValue(rank.getValue().toString());
                    }
                }
            }
            respMsg.setValue(String.valueOf(unionData.getScore()));
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_MATH_DETAIL_LIST, respMsg);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
    }

    private RankUnionWarProto.RankUnionWarTeamMatchDetailMsg.Builder parseMatchDetailMsg(CrossRankUnionWarMatchData matchData,long userId){
        BigDecimal support1 = BigDecimal.valueOf(matchData.getUnion1Support());
        BigDecimal support2 = BigDecimal.valueOf(matchData.getUnion2Support());
        BigDecimal supportAll = support1.add(support2);
        RankUnionWarProto.RankUnionWarTeamMatchDetailMsg.Builder matchMsg = RankUnionWarProto.RankUnionWarTeamMatchDetailMsg.newBuilder();
        matchMsg.setGameNo(matchData.getGameNo());
        matchMsg.setGameType(matchData.getDivision());
        matchMsg.setTurn(matchData.getTurn());
        UnionBaseInfo unionBaseInfo = unionDataMap.get(matchData.getUnionId1()).getUnionBaseInfo();
        matchMsg.setTeam1UnionId(matchData.getUnionId1());
        matchMsg.setTeam1UnionInfo(UnionBasePb.parseUnionBaseTempMsg(unionBaseInfo));
        /*BigDecimal a = (supportAll.compareTo(BigDecimal.ZERO) == 0)?BigDecimal.ONE:support1.multiply(BigDecimal.valueOf(100).divide(supportAll,0, BigDecimal.ROUND_HALF_UP));
        BigDecimal b = (supportAll.compareTo(BigDecimal.ZERO) == 0)?BigDecimal.ONE:support1.multiply(BigDecimal.valueOf(100).divide(supportAll,1, BigDecimal.ROUND_HALF_UP));
        b = b.setScale(0,BigDecimal.ROUND_HALF_UP);*/
        matchMsg.setTeam1Support(supportAll.compareTo(BigDecimal.ZERO) == 0?0:support1.multiply(BigDecimal.valueOf(100).divide(supportAll,4, BigDecimal.ROUND_HALF_UP)).setScale(0,BigDecimal.ROUND_HALF_UP).intValue());
        matchMsg.setTeam2UnionId(matchData.getUnionId2());
        matchMsg.setNo(matchData.getNo());
        Map<Integer, CrossRankUnionWarLineData> lineDataMap = matchData.getBattleLineMap();
        for(int line = 1; line <= 5 ;line++){
            matchMsg.addLineWinner(lineDataMap.get(line).getWinUnionId());
        }
        if(!StringUtils.isNullOrEmpty(matchData.getUnionId2())){
            UnionBaseInfo union2BaseInfo = unionDataMap.get(matchData.getUnionId2()).getUnionBaseInfo();
            matchMsg.setTeam2UnionInfo(UnionBasePb.parseUnionBaseTempMsg(union2BaseInfo));
            matchMsg.setTeam2Support(supportAll.compareTo(BigDecimal.ZERO) == 0?0:support2.multiply(BigDecimal.valueOf(100)).divide(supportAll,4, BigDecimal.ROUND_HALF_UP).setScale(0,BigDecimal.ROUND_HALF_UP).intValue());
        }
        matchMsg.setStatus(matchData.getStatus());
        //比赛会提前结束，提前结束先发状态2给客户端，服务端状态2的时候会同时触发移除数据晋级选队，要同时统一处理
        if(!StringUtils.isNullOrEmpty(matchData.getWinUnionId())){
            matchMsg.setStatus(2);
        }
        matchMsg.setWinUnionId(matchData.getWinUnionId());
        if(gambleMap.containsKey(matchData.getTurn())){
            Map<Integer, String> guessMap = gambleMap.get(matchData.getTurn()).getGuessUnionIdMap().get(userId);
            if(guessMap != null){
                matchMsg.setGamblingUnionId(guessMap.getOrDefault(matchData.getGameNo(),""));
            }
        }
        return matchMsg;
    }

    //门客已经上阵了，然后装上了已经绑定的珍兽或者鱼，要下架
    private void checkUnLoadWaitPatrons(CrossRankUnionWarWaitPatronData waitPatronData){
        if(isPatronsVehicleLock(waitPatronData) || isPatronsFishLock(waitPatronData) || isPatronsCricketLock(waitPatronData)){
            waitPatronData.setLine(0);
            logger.info("巅峰活动{},玩家{}的门客{}因为上了锁定的珍兽或鱼被强制下线了",
                    getActivityId(),waitPatronData.getUserId(),waitPatronData.getUserId());
        }
    }

    //设置商会成员的门客信息
    public void setPatronsInfo(RankUnionWarProto.CrossRankUnionWarGetPatronsRespMsg reqMsg) {
        long begin = System.currentTimeMillis();

        Map<String, Map<Long, Set<Integer>>> patronsChangeMap = new HashMap<>();

        for(RankUnionWarProto.CrossRankUnionWarPatronsUpdateMsg userMsg: reqMsg.getUsersList()){
            CrossRankUnionWarUnionData unionData = unionDataMap.get(userMsg.getUnionUid());
            if(unionData == null){
                logger.info("巅峰{}找不到玩家{}的商会{}",getActivityId(),userMsg.getUserId(),userMsg.getUnionUid());
                continue;
            }

            synchronized (unionData){
                Map<Long, CrossRankUnionWarMemberData> memberDataMap = unionData.getMemberMap();
                CrossRankUnionWarMemberData memberData = memberDataMap.get(userMsg.getUserId());
                if(memberData == null){
                    logger.info("巅峰{}找不到玩家{}的商会成员信息{}",getActivityId(),userMsg.getUserId(),userMsg.getUnionUid());
                    continue;
                }
                if(memberData.getPatronDataMap(reqMsg.getTurn()) == null){
                    memberData.setPatronDataMap(reqMsg.getTurn(),new ConcurrentHashMap<>());
                }
                Map<Integer, CrossRankUnionWarPatronData> patronDataMap = memberData.getPatronDataMap(reqMsg.getTurn());
                for(RankUnionWarProto.CrossRankUnionWarPatronsMsg patronsMsg: userMsg.getPatronsList()){
                    if(patronDataMap.containsKey(patronsMsg.getPatronsId())){
                        CrossRankUnionWarPatronData patronData = patronDataMap.get(patronsMsg.getPatronsId());
                        patronData.setEarnSpeed(new BigInteger(patronsMsg.getEarnSpeed()));
                        patronData.setSkinId(patronsMsg.getSkinId());
                        patronData.setVehicleUid(patronsMsg.getVehicleUid());
                        patronData.setFishId(patronsMsg.getFishId());
                        patronData.setPromotionId(patronsMsg.getPromotionId());
                        patronData.setCricketId(patronsMsg.getCricketId());
                    }else{
                        CrossRankUnionWarPatronData patronData = new CrossRankUnionWarPatronData();
                        patronData.setUserId(userMsg.getUserId());
                        patronData.setPatronsId(patronsMsg.getPatronsId());
                        patronData.setEarnSpeed(new BigInteger(patronsMsg.getEarnSpeed()));
                        patronData.setSkinId(patronsMsg.getSkinId());
                        patronData.setPromotionId(patronsMsg.getPromotionId());
                        patronData.setVehicleUid(patronsMsg.getVehicleUid());
                        patronData.setFishId(patronsMsg.getFishId());
                        patronData.setCricketId(patronsMsg.getCricketId());
                        patronDataMap.put(patronData.getPatronsId(),patronData);
                    }
                }
                memberData.setPatronDataMap(reqMsg.getTurn(),patronDataMap);
                if(!memberData.getIsGetPatronsMap().contains(reqMsg.getTurn())){
                    memberData.getIsGetPatronsMap().add(reqMsg.getTurn());
                }
                unionData.setMemberMap(memberDataMap);
                Map<Long, Set<Integer>> userPatronsListMap = patronsChangeMap.get(unionData.getUnionId());
                if (userPatronsListMap == null) {
                    userPatronsListMap = new HashMap<>();
                    patronsChangeMap.put(unionData.getUnionId(), userPatronsListMap);
                }
                Set<Integer> patronsIdList = userPatronsListMap.get(userMsg.getUserId());
                if (patronsIdList == null) {
                    patronsIdList = new HashSet<>();
                    userPatronsListMap.put(userMsg.getUserId(), patronsIdList);
                }
                for (RankUnionWarProto.CrossRankUnionWarPatronsMsg msg : userMsg.getPatronsList()) {
                    patronsIdList.add(msg.getPatronsId());
                }
            }
        }
        // 先注释 用下面调用
      /*  for(RankUnionWarProto.CrossRankUnionWarPatronsUpdateMsg userMsg: reqMsg.getUsersList()){
            CrossRankUnionWarUnionData unionData = unionDataMap.get(userMsg.getUnionUid());
            if(unionData == null){
                continue;
            }
            updateMatchWaitPatrons(unionData,reqMsg.getTurn());
        }*/
        updateWaitPatronsList(reqMsg.getTurn(),patronsChangeMap);
        long end = System.currentTimeMillis();
//        logger.info("sync patrons cost {} ms", (end - begin));

    }
    //更新需要更新的门客的数据
    private void updateWaitPatronsList(int turn,Map<String, Map<Long, Set<Integer>>> patronsChangeMap){
        // 遍历 更新的门客
        for (Map.Entry<String, Map<Long, Set<Integer>>> entry : patronsChangeMap.entrySet()) {
            String unionId = entry.getKey();
            CrossRankUnionWarUnionData unionData = unionDataMap.get(unionId);
            if (unionData == null) {
                continue;
            }
            Map<Long, Set<Integer>> memberMap = entry.getValue();
            CrossRankUnionWarMatchData matchData = getIngGameNoMatch(unionData.getUnionId());
            if(matchData == null){
                continue;
            };
            //防止更新一半的时候比赛被标记开始了，数据就会不一致，上场的门客和备战的血量不一样
            synchronized (matchData){
                if(matchData.getTurn() != turn || matchData.getStatus() != 0){
                    continue;
                }
                Map<Long, Map<Integer, CrossRankUnionWarWaitPatronData>> waitPatronsMap = new ConcurrentHashMap<>(matchData.getWaitPatronsMap());
                Map<Long, CrossRankUnionWarMemberData> memberDataMap = unionData.getMemberMap();
                for(long memberUserId : memberMap.keySet()){
                    // 遍历有更新的成员
                    if(waitPatronsMap.containsKey(memberUserId)){
                        Set<Integer> patronsSet = memberMap.get(memberUserId);
                        CrossRankUnionWarMemberData memberData =  memberDataMap.get(memberUserId);
                        if (memberData == null) {
                            continue;
                        }
                        Map<Integer, CrossRankUnionWarPatronData> updatePatronsMap = memberData.getPatronDataMap().get(turn);
                        Map<Integer, CrossRankUnionWarWaitPatronData> dataMap = waitPatronsMap.get(memberUserId);
                        for (Integer patronsId : patronsSet) {
                            if (dataMap.containsKey(patronsId)) {
                                CrossRankUnionWarWaitPatronData waitPatronData = dataMap.get(patronsId);
                                CrossRankUnionWarPatronData updatePatrons = updatePatronsMap.get(waitPatronData.getPatronId());
                                BigInteger updateEarnSpeed = updatePatrons.getEarnSpeed();
                                if(unionData.getUnionId().equals(matchData.getAttackUnionId())){
                                    updateEarnSpeed = updateEarnSpeed.multiply(BigInteger.valueOf(config.getGuwuAdd() + 1000)).divide(BigInteger.valueOf(1000));
                                }
                                waitPatronData.setSkinId(updatePatrons.getSkinId());
                                waitPatronData.setPromotionId(updatePatrons.getPromotionId());
                              /*  if(updateEarnSpeed.compareTo(waitPatronData.getEarnSpeed()) != 0){
                                    logger.error("巅峰{}玩家{},的门客{},更新赚速，原先赚速{},现在赚速{}",getActivityId(),
                                            waitPatronData.getUserId(),waitPatronData.getPatronId(),waitPatronData.getEarnSpeed(),updatePatrons.getEarnSpeed());
                                }*/
                                waitPatronData.setEarnSpeed(updateEarnSpeed);
                                //判断下门客要不要卸载
                                if(waitPatronData.getLine() != 0){
                                    checkUnLoadWaitPatrons(waitPatronData);
                                }
                                addNeedUpdateWaitPatrons(waitPatronData);
                            }else {
                                logger.info("巅峰活动{}玩家{}获得新门客{}备战期加入了",getActivityId(),memberUserId,patronsId);
                                CrossRankUnionWarWaitPatronData waitPatronData = initWaitPatrons(matchData.getGameNo(),memberUserId,updatePatronsMap.get(patronsId));
                                waitPatronsMap.get(memberUserId).put(waitPatronData.getPatronId(),waitPatronData);
                                addNeedInsertWaitPatrons(waitPatronData);
                            }
                        }
                    }
                }
            }
        }
    }

    //门客在备战期赚速变化了要更新
    private void updateMatchWaitPatrons(CrossRankUnionWarUnionData unionData, int turn){
        CrossRankUnionWarMatchData matchData = getIngGameNoMatch(unionData.getUnionId());
        if(matchData == null)return;
        //防止更新一半的时候比赛被标记开始了，数据就会不一致，上场的门客和备战的血量不一样
        synchronized (matchData){
            if(matchData.getTurn() != turn || matchData.getStatus() != 0)return;
            Map<Long, CrossRankUnionWarMemberData> memberDataMap = unionData.getMemberMap();
            Map<Long, Map<Integer, CrossRankUnionWarWaitPatronData>> waitPatronsMap = new ConcurrentHashMap<>(matchData.getWaitPatronsMap());
            for(long memberUserId : memberDataMap.keySet()){
                if(waitPatronsMap.containsKey(memberUserId)){
                    CrossRankUnionWarMemberData memberData =  memberDataMap.get(memberUserId);
                    Map<Integer, CrossRankUnionWarPatronData> updatePatronsMap = memberData.getPatronDataMap().get(turn);
                    for(CrossRankUnionWarWaitPatronData waitPatronData : waitPatronsMap.get(memberUserId).values()){
                        if(updatePatronsMap.containsKey(waitPatronData.getPatronId())){
                            CrossRankUnionWarPatronData updatePatrons = updatePatronsMap.get(waitPatronData.getPatronId());
                            BigInteger updateEarnSpeed = updatePatrons.getEarnSpeed();
                            if(unionData.getUnionId().equals(matchData.getAttackUnionId())){
                                updateEarnSpeed = updateEarnSpeed.multiply(BigInteger.valueOf(config.getGuwuAdd() + 1000)).divide(BigInteger.valueOf(1000));
                            }
                            waitPatronData.setSkinId(updatePatrons.getSkinId());
                            waitPatronData.setPromotionId(updatePatrons.getPromotionId());
                            if(updateEarnSpeed.compareTo(waitPatronData.getEarnSpeed()) != 0){
                                logger.error("巅峰{}玩家{},的门客{},更新赚速，原先赚速{},现在赚速{}",getActivityId(),
                                        waitPatronData.getUserId(),waitPatronData.getPatronId(),waitPatronData.getEarnSpeed(),updatePatrons.getEarnSpeed());
                                waitPatronData.setEarnSpeed(updateEarnSpeed);
                            }
                            //判断下门客要不要卸载
                            if(waitPatronData.getLine() != 0){
                                checkUnLoadWaitPatrons(waitPatronData);
                            }
                            addNeedUpdateWaitPatrons(waitPatronData);
                        }
                    }
                    //新增门客
                    for(int patronsId : updatePatronsMap.keySet()){
                        if(!waitPatronsMap.get(memberUserId).containsKey(patronsId)){
                            logger.info("巅峰活动{}玩家{}获得新门客{}备战期加入了",getActivityId(),memberUserId,patronsId);
                            CrossRankUnionWarWaitPatronData waitPatronData = initWaitPatrons(matchData.getGameNo(),memberUserId,updatePatronsMap.get(patronsId));
                            waitPatronsMap.get(memberUserId).put(waitPatronData.getPatronId(),waitPatronData);
                            addNeedInsertWaitPatrons(waitPatronData);
                        }
                    }
                }
            }
        }
    }

    //获取玩家当前在打哪一场比赛，没有就是0
    private int getMyGameNo(long userId){
        if(!userUnionIdMap.containsKey(userId)){
            return 0;
        }
        for(CrossRankUnionWarMatchData matchData : battlingMatchMap.values()){
            if(matchData.getUnionId1().equals(userUnionIdMap.get(userId))){
                return matchData.getGameNo();
            }
            if(matchData.getUnionId2().equals(userUnionIdMap.get(userId))){
                return matchData.getGameNo();
            }
        }
        return 0;
    }

    //比赛是不是结束了(红点)
    private boolean isMyMatchOver(int gameNo,long userId){
        if(!userUnionIdMap.containsKey(userId)){
            return true;
        }
        CrossRankUnionWarMatchData matchData = getGameNoMatch(gameNo);
        if(matchData == null){
            return true;
        }
        return !StringUtils.isNullOrEmpty(matchData.getWinUnionId());
    }

    //时候有比赛奖励可以领取(红点)
    private boolean canGetMatchReward(long userId){
        CrossRankUnionWarUnionData unionData = getUnionData(userId);
        if(unionData == null){
            return false;
        }
        Map<Integer,CrossRankUnionWarMatchData> tempBattleMatchMap = new ConcurrentHashMap<>(battleMatchMap);
        for(CrossRankUnionWarMatchData matchData : tempBattleMatchMap.values()){
            if(!StringUtils.isNullOrEmpty(matchData.getWinUnionId())){
                if(matchData.getUnionId1().equals(unionData.getUnionId()) || matchData.getUnionId2().equals(unionData.getUnionId())){
                    if(!matchData.getMatchRewardList().contains(userId)){
                        return true;
                    }
                }
            }
        }
        return false;
    }

    //是否需要去任命管理员(红点)
    private boolean needSetCommander(int gameNo,long userId){
        CrossRankUnionWarMatchData matchData = getGameNoMatch(gameNo);
        if(matchData == null){
            return false;
        }
        CrossRankUnionWarUnionData unionData = getUnionData(userId);
        if(unionData == null){
            return false;
        }
        if(!unionData.getMemberMap().containsKey(userId)){
            return false;
        }
        CrossRankUnionWarMemberData memberData = unionData.getMemberMap().get(userId);
        if(memberData.getPosition() != eUnionPosition.Master.getValue() && memberData.getPosition() != eUnionPosition.DeputyMaster.getValue()){
            return false;
        }
        boolean needCommand = false;
        for(CrossRankUnionWarMemberData member : unionData.getMemberMap().values()){
            if(member.getPosition() != eUnionPosition.Master.getValue() && member.getPosition() != eUnionPosition.DeputyMaster.getValue()){
                needCommand = true;
                break;
            }
        }
        if(!needCommand){
            return false;
        }
        if(!unionData.getOpUserIdMap().containsKey(matchData.getGameNo())){
            return false;
        }

        for(List<Long> userIdList : unionData.getOpUserIdMap().get(matchData.getGameNo()).values()){
            if(userIdList.size() == 0){
                return true;
            }
        }
        return false;
    }

    //是否有可以竞猜的还没去竞猜(红点)
    private boolean isMyGamBle(long userId){
        int gameTurn = crossRankUnionWarData.getGameTurn();
        RankUnionWarTimeConfig timeConfig = config.getTimeConfig(gameTurn);
        if(timeConfig == null || System.currentTimeMillis() >= timeConfig.getStartTime()){
            return false;
        }
        if(gambleMap.containsKey(gameTurn)){
            CrossRankUnionWarGambleData gambleData = gambleMap.get(gameTurn);
            if(!gambleData.getGuessUnionIdMap().containsKey(userId)){
                return true;
            }
            if(gambleData.getGuessUnionIdMap().get(userId).size() != gambleData.getGameNoMap().size()){
                return true;
            }
        }
        return false;
    }

    //获取当前赛区
    private int getMyDivision(int gameNo,long userId){
        RankUnionWarTimeConfig lastTimeConfig = config.getLastTimeConfig();
        long nowTime = System.currentTimeMillis();
        if(nowTime > lastTimeConfig.getEndTime()) {
            CrossRankUnionWarUnionData unionData = getUnionData(userId);
            if(unionData != null){
                Map<Integer, List<String>> divisionMap = crossRankUnionWarData.getBattleUnionIdMap().get(lastTimeConfig.getSession());
                if(divisionMap == null){
                    return 0;
                }
                for(int divisionId : divisionMap.keySet()){
                    List<String> unionMap = divisionMap.get(divisionId);
                    if(unionMap.contains(unionData.getUnionId())){
                        return divisionId;
                    }
                }
            }
        }else{
            if(gameNo == 0){
                return 0;
            }
            CrossRankUnionWarMatchData gameMatch = getIngGameNoMatch(gameNo);
            if(gameMatch != null){
                return gameMatch.getDivision();
            }
        }
        return 0;
    }

    //获取还没结束的战斗
    private CrossRankUnionWarMatchData getIngGameNoMatch(int gameNo){
        if(!battlingMatchMap.containsKey(gameNo)){
            return null;
        }
        return battlingMatchMap.get(gameNo);
    }

    private CrossRankUnionWarMatchData getIngGameNoMatch(String unionId){
        for(CrossRankUnionWarMatchData matchData : battlingMatchMap.values()){
            if(matchData.getUnionId1().equals(unionId)){
                return matchData;
            }
            if(matchData.getUnionId2().equals(unionId)){
                return matchData;
            }
        }
        return null;
    }

    private CrossRankUnionWarMatchData getGameNoMatch(int gameNo){
        if(!battleMatchMap.containsKey(gameNo)){
            return null;
        }
        return battleMatchMap.get(gameNo);
    }

    //获取当前正在比赛的队伍
    private CrossRankUnionWarMatchData getUnionMatch(String unionId){
        for(CrossRankUnionWarMatchData matchData : battlingMatchMap.values()){
            if(matchData.getUnionId1().equals(unionId)){
                return matchData;
            }
            if(matchData.getUnionId2().equals(unionId)){
                return matchData;
            }

        }
        return null;
    }

    //玩家登录的时候同步需要同步到本服触发的condition
    public void syncLoginCondition(long serverId, long userId, RankUnionWarProto.CrossRankUnionWarUserDataSyncMsg reqMsg){
        UserBaseInfo userBaseInfo = PlayerBasePb.parseToUserBaseInfo(reqMsg.getPlayerBaseData());
        CrossUserMgr.updateUserBaseInfoChange(userId,userBaseInfo);
        //同步触发的东西
        int division = 0;
        CrossRankUnionWarUnionData unionData = getUnionData(userId);
        if(unionData != null){
            changeUnionActivityValue(unionData.getUnionId(),UnionRiseRankArgs.NOTIFY_TYPE_NORMAL);
            Map<Integer, Map<Integer, List<String>>> dataMap = crossRankUnionWarData.getBattleUnionIdMap();
            for(Map<Integer, List<String>> divisionMap : dataMap.values()){
                for(Integer divisionId : divisionMap.keySet()){
                    for(String unionId : divisionMap.get(divisionId)){
                        if(unionId.equals(unionData.getUnionId()) && divisionId > division){
                            division = divisionId;
                        }
                    }
                }
            }
            if(division != 0){
                addConditionSync(userId,2,BigInteger.valueOf(division),"");
            }
            addConditionSync(userId,1,BigInteger.valueOf(unionData.getMemberMap().get(userId).getKillNum()),"");
//            addConditionSync(userId,3,BigInteger.valueOf(unionData.getScore()),"");
            addConditionSync(userId,5,BigInteger.valueOf(unionData.getWinTimes()),"");
        }
        Map<Integer,CrossRankUnionWarGambleData> tempGambleMap = new ConcurrentHashMap<>(gambleMap);
        for(CrossRankUnionWarGambleData gambleData : tempGambleMap.values()){
            if(gambleData.isOver()){
                if(gambleData.getGuessUnionIdMap().containsKey(userId)){
                    int rightCount = 0;
                    Map<Integer, String> guseeUnionIdMap = gambleData.getGuessUnionIdMap().get(userId);
                    for(String unionId : guseeUnionIdMap.values()){
                        if(gambleData.getWinUnionIdList().contains(unionId)){
                            rightCount ++;
                        }
                    }
                    addConditionSync(userId,4,BigInteger.valueOf(rightCount),getGamebleRightCountString(gambleData.getTurn()));
                }else{
                    addConditionSync(userId,4,BigInteger.valueOf(-1),getGamebleRightCountString(gambleData.getTurn()));
                }
            }
        }
    }

    public void syncUserData(long serverId,long userId) {
        RankUnionWarProto.RankUnionWarNewGameSyncMsg.Builder syncMsg = RankUnionWarProto.RankUnionWarNewGameSyncMsg.newBuilder();
        RankUnionWarProto.RankUnionWarCrossUserDataSyncMsg.Builder userSyncMsg = RankUnionWarProto.RankUnionWarCrossUserDataSyncMsg.newBuilder();
        userSyncMsg.setUserId(userId);
        userSyncMsg.setSyncData(parseUserData(userId));
        syncMsg.addSyncData(userSyncMsg);

        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_CROSS_SYNC_USER_DATA, syncMsg);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, 0, pbMsg);
    }

    public void syncUserData(long serverId, long userId, RankUnionWarProto.CrossRankUnionWarUserDataSyncMsg reqMsg) {
        RankUnionWarProto.RankUnionWarNewGameSyncMsg.Builder syncMsg = RankUnionWarProto.RankUnionWarNewGameSyncMsg.newBuilder();
        RankUnionWarProto.RankUnionWarCrossUserDataSyncMsg.Builder userSyncMsg = RankUnionWarProto.RankUnionWarCrossUserDataSyncMsg.newBuilder();
        userSyncMsg.setUserId(userId);
        userSyncMsg.setSyncData(parseUserData(userId));
        syncMsg.addSyncData(userSyncMsg);

        CrossRankUnionWarMemberData unionMemberData = getUnionMember(userId);
        if(unionMemberData != null){
            int patronsSkillAdd = reqMsg.getPatronsSkillAdd();
            unionMemberData.setPatronsSkillAdd(patronsSkillAdd);
        }

        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_CROSS_SYNC_USER_DATA, syncMsg);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, 0, pbMsg);
    }

    private RankUnionWarProto.RankUnionWarUserDataSyncMsg.Builder parseUserData(long userId){
        RankUnionWarProto.RankUnionWarUserDataSyncMsg.Builder syncMsg = RankUnionWarProto.RankUnionWarUserDataSyncMsg.newBuilder();
        syncMsg.setActivityId(getActivityId());
        CrossRankUnionWarUnionData unionData = getUnionData(userId);
        syncMsg.setGameNo(0);
        syncMsg.setDivision(0);
        syncMsg.setEliminate(false);
        syncMsg.setMatchOver(false);
        syncMsg.setIsGamble(isMyGamBle(userId));
        syncMsg.setCanGetMatchReward(false);
        syncMsg.setNeedSetCommand(false);
        if(unionData != null && unionData.getMemberMap().containsKey(userId)){
            if(!unionData.getMemberMap().get(userId).isQuit()){
                int gameNo = getMyGameNo(userId);
                syncMsg.setGameNo(gameNo);
                syncMsg.setDivision(getMyDivision(gameNo,userId));
                syncMsg.setEliminate(unionData.isDie());
                syncMsg.setMatchOver(isMyMatchOver(gameNo,userId));
                syncMsg.setCanGetMatchReward(canGetMatchReward(userId));
                syncMsg.setNeedSetCommand(needSetCommander(gameNo,userId));
            }
            syncMsg.setUnionId(unionData.getUnionId());
        }
        UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(userId);
        if(userBaseInfo != null){
            CrossRankUnionWarUnionData unionDataJoin = getUnionData(userBaseInfo.getUnionUid());
            if(unionDataJoin != null){
                for(CrossRankUnionWarMemberData memberData : unionDataJoin.getMemberMap().values()){
                    RankUnionWarProto.RankUnionWarUnionMember.Builder memMsg = RankUnionWarProto.RankUnionWarUnionMember.newBuilder();
                    memMsg.setUserId(memberData.getUserId());
                    UserBaseInfo memBaseInfo = CrossUserMgr.getUserBaseInfo(memberData.getUserId());
                    if(memBaseInfo == null)continue;
                    memMsg.setNickName(memBaseInfo.getNickName());
                    syncMsg.addMembers(memMsg);
                }
            }
        }
        return syncMsg;
    }

    //获取备战信息
    public void deployInfo(long serverId,long userId,RankUnionWarProto.RankUnionWarDeployReqMsg reqMsg) {
        RankUnionWarProto.RankUnionWarDeployRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarDeployRespMsg.newBuilder();
        respMsg.setRet(0);
        if(!battlingMatchMap.containsKey(reqMsg.getGameNo())){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAME_OVER);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_DEPLOY, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        CrossRankUnionWarMatchData matchData = battlingMatchMap.get(reqMsg.getGameNo());
        CrossRankUnionWarUnionData unionData = getUnionData(userId);
        if(unionData == null || (!unionData.getUnionId().equals(matchData.getUnionId1()) && !unionData.getUnionId().equals(matchData.getUnionId2()))){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_DEPLOY_ERROR_GAME);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_DEPLOY, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        UnionBaseInfo union1BaseInfo = getUnionBaseInfo(matchData.getUnionId1());
        respMsg.setTeam1UnionId(matchData.getUnionId1());
        respMsg.setTeam1UnionInfo(UnionBasePb.parseUnionBaseTempMsg(union1BaseInfo));
        respMsg.setTeam1Morale(matchData.getMorale1());
        UnionBaseInfo union2BaseInfo = getUnionBaseInfo(matchData.getUnionId2());
        respMsg.setTeam2UnionId(matchData.getUnionId2());
        if(union2BaseInfo != null){
            respMsg.setTeam2UnionInfo(UnionBasePb.parseUnionBaseTempMsg(union2BaseInfo));
            respMsg.setTeam2Morale(matchData.getMorale2());
        }
        //士气点数就是鼓舞次数
        if(unionData.getUnionId().equals(matchData.getUnionId1())){
            respMsg.setInspireTimes(matchData.getMorale1());
        }else{
            respMsg.setInspireTimes(matchData.getMorale2());
        }
        respMsg.setMyInspireTimes(matchData.getUserInspireTimesMap().getOrDefault(userId,0));

        respMsg.addAllUnion1PatronsNum(getMatchUnion1LineCountList(matchData));
        respMsg.addAllUnion2PatronsNum(getMatchUnion2LineCountList(matchData));

        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_DEPLOY, respMsg);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);

    }

    private UnionBaseInfo getUnionBaseInfo(String unionId){
        if(!unionDataMap.containsKey(unionId)){
            return null;
        }
        return unionDataMap.get(unionId).getUnionBaseInfo();
    }

    //获取自己战斗队伍的每条线上上场门客，备战使用
    private List<Integer> getMatchUnion1LineCountList(CrossRankUnionWarMatchData matchData){
        Map<Integer,Integer> lineCountMap = new ConcurrentHashMap<>();
        List<Integer> patronCountList = new ArrayList<>();
        Map<Long, Map<Integer, CrossRankUnionWarWaitPatronData>> userPatronsMap = new ConcurrentHashMap<>(matchData.getWaitPatronsMap());
        for(long userId : userPatronsMap.keySet()){
            CrossRankUnionWarUnionData unionData = getUnionData(userId);
            if(unionData != null && unionData.getUnionId().equals(matchData.getUnionId1())){
                for(CrossRankUnionWarWaitPatronData warWaitPatronData : userPatronsMap.get(userId).values()){
                    int line  = warWaitPatronData.getLine();
                    if(line != 0){
                        lineCountMap.put(line,lineCountMap.getOrDefault(line,0) + 1);
                    }
                }
            }
        }
        for(int line = 1; line <= 5;line++){
            patronCountList.add(lineCountMap.getOrDefault(line,0));
        }
        return patronCountList;
    }

    private List<Integer> getMatchUnion2LineCountList(CrossRankUnionWarMatchData matchData){
        List<Integer> patronCountList = new ArrayList<>();
        if(StringUtils.isNullOrEmpty(matchData.getUnionId2())){
            return patronCountList;
        }
        Map<Integer,Integer> lineCountMap = new ConcurrentHashMap<>();
        Map<Long, Map<Integer, CrossRankUnionWarWaitPatronData>> userPatronsMap = new ConcurrentHashMap<>(matchData.getWaitPatronsMap());
        for(long userId : userPatronsMap.keySet()){
            CrossRankUnionWarUnionData unionData = getUnionData(userId);
            if(unionData != null && unionData.getUnionId().equals(matchData.getUnionId2())){
                for(CrossRankUnionWarWaitPatronData warWaitPatronData : userPatronsMap.get(userId).values()){
                    int line  = warWaitPatronData.getLine();
                    if(line != 0){
                        lineCountMap.put(line,lineCountMap.getOrDefault(line,0) + 1);
                    }
                }
            }
        }
        for(int line = 1; line <= 5;line++){
            patronCountList.add(lineCountMap.getOrDefault(line,0));
        }
        return patronCountList;
    }

    //招募门客列表
    public void recruitPatronsList(long serverId, long userId, RankUnionWarProto.RankUnionWarRecruitPatronsListReqMsg reqMsg) {
        RankUnionWarProto.RankUnionWarRecruitPatronsListRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarRecruitPatronsListRespMsg.newBuilder();
        respMsg.setRet(0);
        CrossRankUnionWarMatchData matchData = getIngGameNoMatch(reqMsg.getGameNo());
        if(matchData == null){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAME_OVER);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_LIST, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        Map<Integer, CrossRankUnionWarPatronData> patronDataMap = getUserPatronsMap(userId, matchData.getTurn());
        if(patronDataMap == null){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_WAIT_SYNC);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_LIST, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        for(CrossRankUnionWarPatronData patronData : patronDataMap.values()){
            RankUnionWarProto.RankUnionWarPatronBuyMsg.Builder patronsMsg = RankUnionWarProto.RankUnionWarPatronBuyMsg.newBuilder();
            patronsMsg.setPatronsId(patronData.getPatronsId());
            patronsMsg.setBuyTime(patronData.getBuyMap().getOrDefault(reqMsg.getGameNo(),0));
            respMsg.addPatrons(patronsMsg);
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_LIST, respMsg);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
    }

    //招募门客，没有发消耗就先算消耗再下去一遍
    public void recruitPatrons(long serverId, long userId, RankUnionWarProto.RankUnionWarPatronsRecruitReqMsg reqMsg) {
        /*RankUnionWarProto.CrossRankUnionWarPatronsRecruitRespMsg.Builder respMsg = RankUnionWarProto.CrossRankUnionWarPatronsRecruitRespMsg.newBuilder();
        respMsg.setRet(0);
        if(reqMsg.hasCost()){
            respMsg.setCost(reqMsg.getCost());
        }
        CrossRankUnionWarMatchData matchData = getIngGameNoMatch(reqMsg.getGameNo());
        if(matchData == null){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAME_OVER);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_RECRUIT_PATRONS_RES, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        if(matchData.getStatus() == 2){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_MATCH_IS_GOING);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_RECRUIT_PATRONS_RES, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        List<Integer> patronsIdList = reqMsg.getPatronsIdList();
        Map<Integer, CrossRankUnionWarPatronData> patronDataMap = getUserPatronsMap(userId);
        if(patronDataMap == null){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_WAIT_SYNC);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_RECRUIT_PATRONS_RES, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return ;
        }
        int costAll = 0;
        for(Integer patronsId : patronsIdList){
            CrossRankUnionWarPatronData patronData = patronDataMap.get(patronsId);
            if(patronData == null){
                respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_WAIT_SYNC);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_RECRUIT_PATRONS_RES, respMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                return;
            }
            if(patronData.getBuyMap().getOrDefault(reqMsg.getGameNo(),0) >= config.getPatronsBuyMaxTimes()){
                respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_RECRUIT_MAX_TIMES);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_RECRUIT_PATRONS_RES, respMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                return;
            }
            int times = patronData.getBuyMap().getOrDefault(reqMsg.getGameNo(),0) + 1;
            int cost = config.getPatronsBuyTimeCost(times);
            costAll = costAll + cost;
        }
        if(reqMsg.hasCost()){
            if(reqMsg.getCost() != costAll){
                respMsg.setCost(costAll);
                respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_RECRUIT_COST_ERR);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_RECRUIT_PATRONS_RES, respMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            }
            Map<Long, Map<Integer, CrossRankUnionWarBattlePatronData>> userWaitPatronsMap = matchData.getWaitPatronsMap();
            Map<Integer,CrossRankUnionWarBattlePatronData> waitPatronsMap = userWaitPatronsMap.get(userId);
            for(Integer patronsId : patronsIdList){
                CrossRankUnionWarPatronData patronData = patronDataMap.get(patronsId);
                if(patronData == null){
                    continue;
                }
                CrossRankUnionWarBattlePatronData battlePatronData = initBattlePatrons(matchData.getGameNo(),userId,patronData);
                waitPatronsMap.put(battlePatronData.getPatronsNo(),battlePatronData);
                patronData.getBuyMap().put(reqMsg.getGameNo(),patronData.getBuyMap().getOrDefault(reqMsg.getGameNo(),0) + 1);
            }
            //保存数据 门客招募次数
            setUnionDataUpdate(userId);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_RECRUIT_PATRONS_RES, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
        }else{
            RankUnionWarProto.RankUnionWarPatronsRecruitReqMsg.Builder newReqMsg = reqMsg.toBuilder();
            newReqMsg.setCost(costAll);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_PATRONS_RECRUIT, newReqMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
        }*/
    }


    //分页获取每条线上的派遣好的门客
    public void getReadyPatronsList(long serverId, long userId, RankUnionWarProto.RankUnionWarGetSendPatronListReqMsg reqMsg) {
        RankUnionWarProto.RankUnionWarGetSendPatronListRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarGetSendPatronListRespMsg.newBuilder();
        respMsg.setRet(0);
        CrossRankUnionWarMatchData matchData = getGameNoMatch(reqMsg.getGameNo());
        if(matchData == null){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_MATCH_NOT_OVER);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_GET_READY_PATRONS, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        if(matchData.getStatus() == 0){
            Map<Integer, Map<String, List<CrossRankUnionWarWaitPatronData>>> patronsMap = matchData.getReadyPatronsSortMap();
            CrossRankUnionWarUnionData unionData = getUnionData(userId);
            if(patronsMap != null && unionData != null){
                List<CrossRankUnionWarWaitPatronData> list = new ArrayList<>(patronsMap.get(reqMsg.getLine()).get(unionData.getUnionId()));
                int page = reqMsg.getPage();
                for(int i = pagePatronsNum * (page - 1); i < pagePatronsNum * page; i++){
                    if(i >= list.size())break;
                    RankUnionWarProto.RankUnionWarReadyPatronMsg.Builder readyPatronMsg = parseReadyWaitPatron(list.get(i));
                    if(readyPatronMsg == null){
                        continue;
                    }
                    respMsg.addReadyPatrons(readyPatronMsg);
                }
            }
        }
        if(matchData.getStatus() == 1){
            Map<Integer, CrossRankUnionWarLineData> lineDataMap = matchData.getBattleLineMap();
            CrossRankUnionWarLineData lineData = lineDataMap.get(reqMsg.getLine());
            CrossRankUnionWarUnionData unionData = getUnionData(userId);
            if(unionData != null){
                int page = reqMsg.getPage();
                List<CrossRankUnionWarBattlePatronData> list = new ArrayList<>();
                Map<Integer, CrossRankUnionWarBattlePatronData> patronsMap = new ConcurrentHashMap<>(lineData.getBattlePatronsMap().get(unionData.getUnionId()));
                for(int i = 1; i <= patronsMap.size();i++){
                    if(!patronsMap.get(i).isDie()){
                        list.add(patronsMap.get(i));
                        if(list.size() > pagePatronsNum * page){
                            break;
                        }
                    }
                }
                for(int i = pagePatronsNum * (page - 1); i < pagePatronsNum * page; i++){
                    if(i >= list.size())break;
                    RankUnionWarProto.RankUnionWarReadyPatronMsg.Builder readyPatronMsg = parseReadyBattlePatron(list.get(i));
                    if(readyPatronMsg == null){
                        continue;
                    }
                    respMsg.addReadyPatrons(readyPatronMsg);
                }
            }
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_GET_READY_PATRONS, respMsg);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
    }

    private void syncBattlePatronsCount(){
        List<CrossRankUnionWarMatchData> needSyncList = new ArrayList<>();
        synchronized (needSyncMatchCountList){
            if(needSyncMatchCountList.size() > 0){
                needSyncList = new ArrayList<>(needSyncMatchCountList);
            }
            needSyncMatchCountList.clear();
        }
        if(needSyncList.size() > 0){
            RankUnionWarProto.CrossRankUnionWarGameSync.Builder syncMsg = RankUnionWarProto.CrossRankUnionWarGameSync.newBuilder();
            for(CrossRankUnionWarMatchData matchData : needSyncList){
                syncMsg.addSyncData(parseRankUnionWarGameSyncMsg(matchData));
            }
            for(long serverId : config.getActivityInfo().getServerIdList()){
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_CROSS_GAME_SYNC, syncMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, 0, pbMsg);
            }
        }
    }

    //出现胜利的同步给客户端
    private void syncBattleWin(){
        List<CrossRankUnionWarMatchData> needSyncList = new ArrayList<>();
        synchronized (needSyncMatchWinList){
            if(needSyncMatchWinList.size() > 0){
                needSyncList = new ArrayList<>(needSyncMatchWinList);
            }
            needSyncMatchWinList.clear();
        }
        if(needSyncList.size() > 0){
            RankUnionWarProto.CrossRankUnionWarGameWinSync.Builder syncMsg = RankUnionWarProto.CrossRankUnionWarGameWinSync.newBuilder();
            for(CrossRankUnionWarMatchData matchData : needSyncList){
                syncMsg.addSyncData(parseRankUnionWarWinSyncMsg(matchData));
            }
            for(long serverId : config.getActivityInfo().getServerIdList()){
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_CROSS_GAME_WIN_SYNC, syncMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, 0, pbMsg);
            }
        }
    }

    //击杀大于多少要出战报
    private void syncBattleNotice(){
        Map<Integer,List<CrossRankUnionWarNoticeData>> needSyncMap = new ConcurrentHashMap<>();
        synchronized (needSyncNoticeMap){
            if(needSyncNoticeMap.size() > 0){
                needSyncMap = new ConcurrentHashMap<>(needSyncNoticeMap);
            }
            needSyncNoticeMap.clear();
        }
        if(needSyncMap.size() > 0){
            RankUnionWarProto.RankUnionWarCrossNoticeSyncMsg.Builder syncMsg = RankUnionWarProto.RankUnionWarCrossNoticeSyncMsg.newBuilder();
            syncMsg.setActivityId(getActivityId());
            for(int gameNo : needSyncMap.keySet()){
                RankUnionWarProto.RankUnionWarCrossNoticeMsg.Builder gameNoticeMsg = RankUnionWarProto.RankUnionWarCrossNoticeMsg.newBuilder();
                gameNoticeMsg.setGameNo(gameNo);
                for(CrossRankUnionWarNoticeData noticeData : needSyncMap.get(gameNo)){
                    UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(noticeData.getUserId());
                    if(userBaseInfo == null)continue;
                    RankUnionWarProto.RankUnionWarPatronsKillNoticeMsg.Builder noticeMsg = RankUnionWarProto.RankUnionWarPatronsKillNoticeMsg.newBuilder();
                    noticeMsg.setNo(noticeData.getNo());
                    noticeMsg.setUserId(noticeData.getUserId());
                    noticeMsg.setPatronId(noticeData.getPatronId());
                    noticeMsg.setKillTimes(noticeData.getKillTimes());
                    noticeMsg.setTimes(noticeData.getNoticeTime());
                    noticeMsg.setEnemyUnionName(getUnionData(noticeData.getEnemyUnionId()).getUnionBaseInfo().getUnionName());
                    noticeMsg.setPlayerBaseData(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
                    gameNoticeMsg.addNotices(noticeMsg);
                }
                syncMsg.addGameNotices(gameNoticeMsg);
            }
            for(long serverId : config.getActivityInfo().getServerIdList()){
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_CROSS_NOTICE_SYNC, syncMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, 0, pbMsg);
            }
        }
    }

    private void syncBarrage(){
        Map<Integer,List<CrossRankUnionWarBarrageData>> needSyncMap = new ConcurrentHashMap<>();
        synchronized (needSyncBarrageMap){
            if(needSyncBarrageMap.size() > 0){
                needSyncMap = new ConcurrentHashMap<>(needSyncBarrageMap);
            }
            needSyncBarrageMap.clear();
        }
        if(needSyncMap.size() > 0){
            RankUnionWarProto.CrossRankUnionWarBarrageSyncMsg.Builder syncMsg = RankUnionWarProto.CrossRankUnionWarBarrageSyncMsg.newBuilder();
            syncMsg.setActivityId(getActivityId());
            for(int gameNo : needSyncMap.keySet()){
                RankUnionWarProto.CrossRankUnionWarGameNoBarrageMsg.Builder gameBarrageMsg = RankUnionWarProto.CrossRankUnionWarGameNoBarrageMsg.newBuilder();
                gameBarrageMsg.setGameNo(gameNo);
                for(CrossRankUnionWarBarrageData barrageData : needSyncMap.get(gameNo)){
                    UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(barrageData.getUserId());
                    if(userBaseInfo == null)continue;
                    RankUnionWarProto.RankUnionWarBarrageMsg.Builder noticeMsg = RankUnionWarProto.RankUnionWarBarrageMsg.newBuilder();
                    noticeMsg.setNo(barrageData.getBarrageNo());
                    noticeMsg.setUserId(barrageData.getUserId());
                    noticeMsg.setNickName(userBaseInfo.getNickName());
                    noticeMsg.setGameNo(barrageData.getGameNo());
                    noticeMsg.setContent(barrageData.getContent());
                    noticeMsg.setTime(barrageData.getTime());
                    gameBarrageMsg.addBarrages(noticeMsg);
                }
                syncMsg.addGameNoBarrages(gameBarrageMsg);
            }
            for(long serverId : config.getActivityInfo().getServerIdList()){
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_CROSS_BARRAGE_SYNC, syncMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, 0, pbMsg);
            }
        }
    }

    //同步成就
    private void syncCondition(){
        //serverId
        Map<Long,RankUnionWarProto.RankUnionWarCrossConditionSyncMsg.Builder> syncMap = new ConcurrentHashMap<>();
        Map<Long,List<CrossRankUnionConditionSyncData>> needSyncMap = new ConcurrentHashMap<>();
        synchronized (needSyncConditionMap){
            if(needSyncConditionMap.size() > 0){
                needSyncMap = new ConcurrentHashMap<>(needSyncConditionMap);
            }
            needSyncConditionMap.clear();
        }
        if(needSyncMap.size() > 0){
            for(long userId : needSyncMap.keySet()){
                List<CrossRankUnionConditionSyncData> syncList = needSyncMap.get(userId);
                for(CrossRankUnionConditionSyncData syncData : syncList){
                    if(!syncMap.containsKey(syncData.getServerId())){
                        RankUnionWarProto.RankUnionWarCrossConditionSyncMsg.Builder syncMsg = RankUnionWarProto.RankUnionWarCrossConditionSyncMsg.newBuilder();
                        syncMsg.setActivityId(getActivityId());
                        syncMap.put(syncData.getServerId(),syncMsg);
                    }
                    RankUnionWarProto.RankUnionWarCrossConditionMsg.Builder gameConditionMsg = RankUnionWarProto.RankUnionWarCrossConditionMsg.newBuilder();
                    gameConditionMsg.setUserId(userId);
                    gameConditionMsg.setType(syncData.getType());
                    gameConditionMsg.setValue(syncData.getValue().toString());
                    gameConditionMsg.setParam(syncData.getParam());
                    syncMap.get(syncData.getServerId()).addSyncData(gameConditionMsg);
                }
            }
            for(long serverId : syncMap.keySet()){
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_CROSS_CONDITION_SYNC, syncMap.get(serverId));
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, 0, pbMsg);
            }
        }
    }

    //派遣的时候同步门客总数
    private RankUnionWarProto.RankUnionWarGameSyncMsg.Builder parseRankUnionWarGameSyncMsg(CrossRankUnionWarMatchData battleMatch){
        RankUnionWarProto.RankUnionWarGameSyncMsg.Builder respMsg = RankUnionWarProto.RankUnionWarGameSyncMsg.newBuilder();
        respMsg.setGameNo(battleMatch.getGameNo());
        for(CrossRankUnionWarLineData lineData : battleMatch.getBattleLineMap().values()){
            RankUnionWarProto.RankUnionWarGameLineSyncMsg.Builder lineMsg = RankUnionWarProto.RankUnionWarGameLineSyncMsg.newBuilder();
            lineMsg.setLine(lineData.getLine());
            lineMsg.setTeam1Count(lineData.getBattlePatronsMap().get(lineData.getUnionId1()).size());
            lineMsg.setTeam2Count(lineData.getBattlePatronsMap().get(lineData.getUnionId2()).size());
            lineMsg.setTeam1BattleCount(getLineBattlePatronsCount(battleMatch,lineData,battleMatch.getUnionId1()));
            lineMsg.setTeam2BattleCount(getLineBattlePatronsCount(battleMatch,lineData,battleMatch.getUnionId2()));
            lineMsg.setStartWaitTime(lineData.getUnion1StartWaitTime() == 0?lineData.getUnion2StartWaitTime():lineData.getUnion1StartWaitTime());
            lineMsg.setTeam1WaitTime(lineData.getUnion1WaitTime());
            lineMsg.setTeam2WaitTime(lineData.getUnion2WaitTime());
            respMsg.addLine(lineMsg);
        }
        return respMsg;
    }

    //获取线路上门客战斗总数量，在场的和复活的加一起
    private int getLineBattlePatronsCount(CrossRankUnionWarMatchData battleMatch,CrossRankUnionWarLineData lineData,String unionId){
        int battleCount = 0;
        CrossRankUnionWarUnionData union1Data = getUnionData(unionId);
        if(union1Data == null){
            return battleCount;
        }
        Map<Long, Map<Integer, CrossRankUnionWarWaitPatronData>> userWaitPatronsMap = new ConcurrentHashMap<>(battleMatch.getWaitPatronsMap());
        for(CrossRankUnionWarMemberData memberData : union1Data.getMemberMap().values()){
            if(userWaitPatronsMap.containsKey(memberData.getUserId())){
                for(CrossRankUnionWarWaitPatronData waitPatrons : userWaitPatronsMap.get(memberData.getUserId()).values()){
                    if(waitPatrons.getLine() != lineData.getLine())continue;
                    CrossRankUnionWarPatronData patronInfoData = getPatronsInfo(waitPatrons.getUserId(),battleMatch.getTurn(),waitPatrons.getPatronId());
                    if(patronInfoData != null){
//                        battleCount = battleCount + (1 + patronInfoData.getBuyMap().getOrDefault(waitPatrons.getGameNo(),0) - getPatronsDieTimes(waitPatrons));
                        battleCount = battleCount + (1 + patronInfoData.getBuyMap().getOrDefault(waitPatrons.getGameNo(),0));
                    }else{
                        logger.error("巅峰{}出现找不到玩家身上的门客了gameNo:{},userId:{},patronsId:{}",getActivityId(),
                                battleMatch.getGameNo(),waitPatrons.getUserId(),waitPatrons.getPatronId());
                    }
                }
            }
        }
        return battleCount;
    }

    //同步胜利的
    private RankUnionWarProto.RankUnionWarWinSyncMsg.Builder parseRankUnionWarWinSyncMsg(CrossRankUnionWarMatchData battleMatch){
        RankUnionWarProto.RankUnionWarWinSyncMsg.Builder respMsg = RankUnionWarProto.RankUnionWarWinSyncMsg.newBuilder();
        respMsg.setActivityId(getActivityId());
        respMsg.setGameNo(battleMatch.getGameNo());
        respMsg.setWinUnionUid("");
        respMsg.setTime(0);
        if(!StringUtils.isNullOrEmpty(battleMatch.getWinUnionId())){
            respMsg.setWinUnionUid(battleMatch.getWinUnionId());
            respMsg.setTime(battleMatch.getWinTime());
        }
        for(CrossRankUnionWarLineData lineData : battleMatch.getBattleLineMap().values()){
            if(!StringUtils.isNullOrEmpty(lineData.getWinUnionId())){
                RankUnionWarProto.RankUnionWarLineWinSyncMsg.Builder lineMsg = RankUnionWarProto.RankUnionWarLineWinSyncMsg.newBuilder();
                lineMsg.setLine(lineData.getLine());
                lineMsg.setWinUnionId(lineData.getWinUnionId());
                lineMsg.setTime(lineData.getWinTime());
                respMsg.addLine(lineMsg);
            }
        }
        return respMsg;
    }


    //分批请求战斗门客
    public void getBattlePatronsList(long serverId, long userId, RankUnionWarProto.RankUnionWarBattlePatronsReqMsg reqMsg) {
        RankUnionWarProto.RankUnionWarBattlePatronsRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarBattlePatronsRespMsg.newBuilder();
        respMsg.setRet(0);
        CrossRankUnionWarMatchData matchData = getIngGameNoMatch(reqMsg.getGameNo());
        if(matchData == null){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAME_OVER);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_GET_BATTLE_PATRONS, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        for(RankUnionWarProto.RankUnionWarBattlePatronsReqInfoMsg infoMsg : reqMsg.getInfosList()){
            CrossRankUnionWarUnionData unionData = getUnionData(infoMsg.getUnionId());
            if(unionData == null){
                respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_WAIT_SYNC);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_GET_BATTLE_PATRONS, respMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                return;
            }
            List<CrossRankUnionWarBattlePatronData> returnPatronList = new ArrayList<>();
            Map<Integer, CrossRankUnionWarLineData> lineDataMap = matchData.getBattleLineMap();
            CrossRankUnionWarLineData lineData = lineDataMap.get(infoMsg.getLine());
            Map<Integer, CrossRankUnionWarBattlePatronData> battlePatronDataMap = new ConcurrentHashMap<>(lineData.getBattlePatronsMap().get(unionData.getUnionId()));
            for(int i = infoMsg.getPatronsIndex() + 1 ; i <= battlePatronDataMap.size();i++){
                CrossRankUnionWarBattlePatronData patronData = battlePatronDataMap.get(i);
                returnPatronList.add(patronData);
                if(returnPatronList.size() >= pagePatronsNum){
                    break;
                }
            }
            for(CrossRankUnionWarBattlePatronData patronData : returnPatronList){
                RankUnionWarProto.RankUnionWarPatronMsg.Builder patronMsg = parsePatronsMsg(infoMsg.getUnionId(),patronData);
                respMsg.addPatrons(patronMsg);
                if(patronData.getBool().equals(BigInteger.ZERO)){
                    logger.error("巅峰{}请求已经死的门客，userId{},patronId{},patronsLineIndex{}",getActivityId(),userId,patronData.getPatronId(),patronData.getLineIndex());
                }
            }
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_GET_BATTLE_PATRONS, respMsg);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
    }

    //派遣门客列表展示
    public void sendPatronsList(long serverId, long userId, RankUnionWarProto.RankUnionWarSendPatronsListReqMsg reqMsg) {
        RankUnionWarProto.RankUnionWarSendPatronsListRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarSendPatronsListRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setActivityId(reqMsg.getActivityId());
        respMsg.setGameNo(reqMsg.getGameNo());
        CrossRankUnionWarMatchData matchData = getIngGameNoMatch(reqMsg.getGameNo());
        if(matchData == null){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAME_OVER);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_SEND_LIST, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        CrossRankUnionWarUnionData unionData = getUnionData(userId);
        if(unionData == null){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_WAIT_SYNC);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_SEND_LIST, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        //准备期的门客
        if(matchData.getStatus() == 0){
            Map<Long, Map<Integer, CrossRankUnionWarWaitPatronData>> waitPatronsMap = new ConcurrentHashMap<>(matchData.getWaitPatronsMap());
            if(waitPatronsMap.containsKey(userId)){
                for(CrossRankUnionWarWaitPatronData waitPatronData : waitPatronsMap.get(userId).values()){
                    RankUnionWarProto.RankUnionWarPatronSendMsg.Builder sendPatronsMsg = parseSendBattlePatron(waitPatronData);
                    if(sendPatronsMsg == null){
                        continue;
                    }
                    respMsg.addSendPatrons(sendPatronsMsg);
                }
            }
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_SEND_LIST, respMsg);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
    }

    private RankUnionWarProto.RankUnionWarReadyPatronMsg.Builder parseReadyWaitPatron(CrossRankUnionWarWaitPatronData waitPatronData){
        RankUnionWarProto.RankUnionWarReadyPatronMsg.Builder readyPatronsMsg = RankUnionWarProto.RankUnionWarReadyPatronMsg.newBuilder();
        readyPatronsMsg.setUserId(waitPatronData.getUserId());
        UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(waitPatronData.getUserId());
        if(userBaseInfo == null){
            return null;
        }
        readyPatronsMsg.setNickName(userBaseInfo.getNickName());
        readyPatronsMsg.setPatronsNo(waitPatronData.getPatronId());
        readyPatronsMsg.setPatronsId(waitPatronData.getPatronId());
        readyPatronsMsg.setEarnSpeed(waitPatronData.getEarnSpeed().toString());
        readyPatronsMsg.setLine(waitPatronData.getLine());
        readyPatronsMsg.setSkinId(waitPatronData.getSkinId());
        readyPatronsMsg.setPromotionId(waitPatronData.getPromotionId());
        return readyPatronsMsg;
    }

    private RankUnionWarProto.RankUnionWarReadyPatronMsg.Builder parseReadyBattlePatron(CrossRankUnionWarBattlePatronData battlePatronData){
        RankUnionWarProto.RankUnionWarReadyPatronMsg.Builder readyPatronsMsg = RankUnionWarProto.RankUnionWarReadyPatronMsg.newBuilder();
        readyPatronsMsg.setUserId(battlePatronData.getUserId());
        UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(battlePatronData.getUserId());
        if(userBaseInfo == null){
            return null;
        }
        readyPatronsMsg.setNickName(userBaseInfo.getNickName());
        readyPatronsMsg.setPatronsNo(battlePatronData.getPatronsNo());
        readyPatronsMsg.setPatronsId(battlePatronData.getPatronId());
        readyPatronsMsg.setEarnSpeed(battlePatronData.getEarnSpeed().toString());
        readyPatronsMsg.setLine(battlePatronData.getLine());
        readyPatronsMsg.setSkinId(battlePatronData.getSkinId());
        readyPatronsMsg.setPromotionId(battlePatronData.getPromotionId());
        return readyPatronsMsg;
    }

    private RankUnionWarProto.RankUnionWarPatronSendMsg.Builder parseSendBattlePatron(CrossRankUnionWarWaitPatronData waitPatronData){
        CrossRankUnionWarMemberData memberData = getUnionMember(waitPatronData.getUserId());
        RankUnionWarProto.RankUnionWarPatronSendMsg.Builder sendPatronsMsg = RankUnionWarProto.RankUnionWarPatronSendMsg.newBuilder();
        sendPatronsMsg.setPatronsId(waitPatronData.getPatronId());
        //原本是门客可以一直招募，同一个门客无限多只，现在改案子变成复活了，不用招募就生成编号了
        sendPatronsMsg.setPatronsNo(waitPatronData.getPatronId());
        sendPatronsMsg.setLine(waitPatronData.getLine());
        if(true || waitPatronData.getLine() != 0 && memberData != null && memberData.getPatronsSkillAdd() != 0){
            BigInteger value = waitPatronData.getEarnSpeed();
            value = value.multiply(BigInteger.valueOf(1000 + memberData.getPatronsSkillAdd()))
                    .divide(BigInteger.valueOf(1000));
            sendPatronsMsg.setEarnSpeed(value.toString());
        }else{
            sendPatronsMsg.setEarnSpeed(waitPatronData.getEarnSpeed().toString());
        }
        sendPatronsMsg.setCanBattleTurn(getPatronsWaitBattleTurn(waitPatronData.getUserId(),waitPatronData.getPatronId()));
        sendPatronsMsg.setVehicleLock(isPatronsVehicleLock(waitPatronData));
        sendPatronsMsg.setFishLock(isPatronsFishLock(waitPatronData));
        sendPatronsMsg.setCricketLock(isPatronsCricketLock(waitPatronData));
        return sendPatronsMsg;
    }

    //获取门客还有多久才能上场
    private int getPatronsWaitBattleTurn(long userId,int patronId){
        CrossRankUnionWarMemberData memberData = getUnionMember(userId);
        if(memberData != null){
            int nowTurn = crossRankUnionWarData.getGameTurn();
            int battleTurn = memberData.getPatronBattleTurnMap().getOrDefault(patronId,0);
            if(battleTurn == 0){
                return 0;
            }else{
                int nextBattle = config.getTurnBattleWait() + battleTurn + 1 - nowTurn;
                return nextBattle < 0 ?0:nextBattle;
            }
        }
        return 0;
    }

    //派遣门客是不是超过了每个职业上线
    private boolean isPatronsOccRight(Map<Integer,CrossRankUnionWarWaitPatronData> userWaitMap,List<Integer> upPatronsIdList,List<Integer> downPatronsIdList){
        Map<Integer,List<Integer>> occPatronMap = new ConcurrentHashMap<>();
        for(eOccupationType occType : eOccupationType.values()){
            occPatronMap.put((int)occType.getValue(),new ArrayList<>());
        }
        for(CrossRankUnionWarWaitPatronData waitPatronData : userWaitMap.values()){
            if(waitPatronData.getLine() != 0){
                PatronsInfo patronsInfo = PatronsMgr.getPatronsInfo(waitPatronData.getPatronId());
                occPatronMap.get(patronsInfo.getOccupation()).add(patronsInfo.getId());
            }
        }
        for(Integer patronsId : upPatronsIdList){
            PatronsInfo patronsInfo = PatronsMgr.getPatronsInfo(patronsId);
            if(!occPatronMap.get(patronsInfo.getOccupation()).contains(patronsInfo.getId())){
                occPatronMap.get(patronsInfo.getOccupation()).add(patronsInfo.getId());
            }
        }
        for(Integer patronsId : downPatronsIdList){
            PatronsInfo patronsInfo = PatronsMgr.getPatronsInfo(patronsId);
            List<Integer> tempList = occPatronMap.get(patronsInfo.getOccupation());
            if(tempList.contains(patronsInfo.getId())){
                tempList.remove(tempList.indexOf(patronsInfo.getId()));
            }
        }
        for(Integer occId : occPatronMap.keySet()){
            if(occPatronMap.get(occId).size() > config.getBattleOccCount()){
                return false;
            }
        }
        return true;
    }

    //派遣上去的门客有没有珍兽和鱼是有限制的
    private boolean isPatronsVehicleLock(CrossRankUnionWarWaitPatronData waitPatronData){
        CrossRankUnionWarPatronData patronData = getPatronsInfo(waitPatronData);
        if(patronData != null && !StringUtils.isNullOrEmpty(patronData.getVehicleUid())){
            Map<String, Integer> vehiclePatronMap = getUserVehiclePatronsMap(patronData.getUserId());
            if(vehiclePatronMap.containsKey(patronData.getVehicleUid())){
                if(vehiclePatronMap.get(patronData.getVehicleUid()) != patronData.getPatronsId()){
                    return true;
                }
            }
        }
        return false;
    }

    private boolean isPatronsFishLock(CrossRankUnionWarWaitPatronData waitPatronData){
        CrossRankUnionWarPatronData patronData = getPatronsInfo(waitPatronData);
        if(patronData != null && patronData.getFishId() != 0){
            Map<Integer, Integer> fishPatronMap = getUserFishPatronsMap(patronData.getUserId());
            if(fishPatronMap.containsKey(patronData.getFishId())){
                if(fishPatronMap.get(patronData.getFishId()) != patronData.getPatronsId()){
                    return true;
                }
            }
        }
        return false;
    }

    private boolean isPatronsCricketLock(CrossRankUnionWarWaitPatronData waitPatronData){
        CrossRankUnionWarPatronData patronData = getPatronsInfo(waitPatronData);
        if(patronData != null && patronData.getCricketId() != 0){
            Map<Integer, Integer> cricketPatronMap = getUserCricketPatronsMap(patronData.getUserId());
            if(cricketPatronMap.containsKey(patronData.getCricketId())){
                if(cricketPatronMap.get(patronData.getCricketId()) != patronData.getPatronsId()){
                    return true;
                }
            }
        }
        return false;
    }

    //派遣门客上线
    public void sendPatrons(long serverId, long userId, RankUnionWarProto.RankUnionWarPatronsSendReqMsg reqMsg) {
        RankUnionWarProto.RankUnionWarPatronsSendRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarPatronsSendRespMsg.newBuilder();
        respMsg.setRet(0);
        CrossRankUnionWarMatchData matchData = getIngGameNoMatch(reqMsg.getGameNo());
        if(matchData == null){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAME_OVER);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_SEND, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        //防止活动状态变成进行的时候并发导致门客多个上阵
        synchronized (matchData){
            if(matchData.getStatus() != 0){
                respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_MATCH_IS_GOING);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_SEND, respMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                return;
            }
            Map<Long, Map<Integer, CrossRankUnionWarWaitPatronData>> waitPatronsMap = new ConcurrentHashMap<>(matchData.getWaitPatronsMap());
            CrossRankUnionWarUnionData unionData = getUnionData(userId);
            if(unionData == null){
                respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_WAIT_SYNC);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_SEND, respMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                return;
            }

            if(reqMsg.getLine() == 0){
                respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_SEND_PATRONS_NO_LINE);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_SEND, respMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                return;
            }

            if(!waitPatronsMap.containsKey(userId)){
                respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_NO_SEND_PATRONS);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_SEND, respMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                return;
            }
            Map<Integer,CrossRankUnionWarWaitPatronData> userWaitMap = waitPatronsMap.get(userId);
            for(int patronsNo: reqMsg.getPatronNosList()){
                if(!userWaitMap.containsKey(patronsNo)){
                    respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_SEND_PATRONS_NOT_EXIT);
                    YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_SEND, respMsg);
                    CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                    return;
                }
                if(getPatronsWaitBattleTurn(userId,patronsNo) != 0){
                    respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_PATRONS_CD_TIME);
                    YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_SEND, respMsg);
                    CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                    return;
                }
                if(isPatronsVehicleLock(userWaitMap.get(patronsNo))){
                    respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_PATRONS_VEHICLE_LOCK);
                    YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_SEND, respMsg);
                    CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                    return;
                }
                if(isPatronsFishLock(userWaitMap.get(patronsNo))){
                    respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_PATRONS_FISH_LOCK);
                    YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_SEND, respMsg);
                    CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                    return;
                }
                if(isPatronsCricketLock(userWaitMap.get(patronsNo))){
                    respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_PATRONS_CRICKET_LOCK);
                    YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_SEND, respMsg);
                    CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                    return;
                }
            }

            if(!isPatronsOccRight(userWaitMap,reqMsg.getPatronNosList(),reqMsg.getUninstallPatronNosList())){
                respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_PATRONS_OCC_MAX);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_SEND, respMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                return;
            }

            //判断这条线是不是挂了
            if(matchData.getStatus() == 1){
                CrossRankUnionWarLineData lineData = matchData.getBattleLineMap().get(reqMsg.getLine());
                if(!StringUtils.isNullOrEmpty(lineData.getWinUnionId())){
                    respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_SEND_PATRONS_LINE_OVER);
                    YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_SEND, respMsg);
                    CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                    return;
                }
            }
            if(matchData.getStatus() == 0){
                for(int uninstallPatronsNo: reqMsg.getUninstallPatronNosList()){
                    uninstallSendPatrons(userWaitMap.get(uninstallPatronsNo));
                }
                for(int patronsNo: reqMsg.getPatronNosList()){
                    addNewSendPatrons(matchData,unionData.getUnionId(),reqMsg.getLine(),userWaitMap.get(patronsNo));
                }
            }else if(matchData.getStatus() == 1){
                //被策划大改成战斗中不能派遣变成复活了
            /*for(int patronsNo: reqMsg.getPatronNosList()){
                CrossRankUnionWarBattlePatronData patronData = userWaitMap.get(patronsNo);
                patronData.setLine(reqMsg.getLine());
                patronData.setSendTime(System.currentTimeMillis());
                userWaitMap.remove(patronsNo);
                CrossRankUnionWarLineData lineData = matchData.getBattlePatronsMap().get(reqMsg.getLine());
                addPatronsToBattleLine(lineData,patronData,true);
            }
            addNeedSyncMatchCountList(matchData);*/
            }
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_SEND, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            sortLineSendPatrons(matchData);
        }
    }

    //新派遣进去的门客放后面排序下需要有个index不能按照派遣时间了，案子变了
    private void addNewSendPatrons(CrossRankUnionWarMatchData matchData,String unionId,int line,CrossRankUnionWarWaitPatronData patronData){
        patronData.setLine(line);
        patronData.setSendTime(System.currentTimeMillis());
        Map<Integer, Map<String, List<CrossRankUnionWarWaitPatronData>>> readyMap = matchData.getReadyPatronsSortMap();
        List<CrossRankUnionWarWaitPatronData> readyList = readyMap.get(patronData.getLine()).get(unionId);
        if(!readyMap.containsKey(patronData.getLine())
                || !readyMap.get(patronData.getLine()).containsKey(unionId)){
            patronData.setLineIndex(1);
        }else{
            patronData.setLineIndex(readyList.size() + 1);
        }
        readyList.add(patronData);
        //todo-xx 多余了，注释掉看看有没有问题
//        matchData.setReadyPatronsSortMap(readyMap);
        addNeedUpdateWaitPatrons(patronData);
    }

    private void uninstallSendPatrons(CrossRankUnionWarWaitPatronData patronData){
        patronData.setLine(0);
        patronData.setSendTime(0);
        addNeedUpdateWaitPatrons(patronData);
    }

    //重新拍一下派遣的列表
    private void sortLineSendPatrons(CrossRankUnionWarMatchData matchData){
        Map<Integer, Map<String,List<CrossRankUnionWarWaitPatronData>>> tempLinePatronsMap = new ConcurrentHashMap<>();
        for(int i = 1; i <= 5; i++){
            if(!tempLinePatronsMap.containsKey(i)){
                Map<String,List<CrossRankUnionWarWaitPatronData>> unionPatronsMapp = new ConcurrentHashMap<>();
                unionPatronsMapp.put(matchData.getUnionId1(),new ArrayList<>());
                unionPatronsMapp.put(matchData.getUnionId2(),new ArrayList<>());
                tempLinePatronsMap.put(i,unionPatronsMapp);
            }
        }
        Map<Long, Map<Integer, CrossRankUnionWarWaitPatronData>> waitPatronsMap = new ConcurrentHashMap<>(matchData.getWaitPatronsMap());
        for(long userId : waitPatronsMap.keySet()){
            Map<Integer, CrossRankUnionWarWaitPatronData> userPatronsMap = waitPatronsMap.get(userId);
            for(CrossRankUnionWarWaitPatronData patronData : userPatronsMap.values()){
                if(patronData.getLine() != 0){
                    CrossRankUnionWarUnionData unionData = getUnionData(patronData.getUserId());
                    if(unionData == null)continue;
                    if(patronData.getLine() <= 0 || patronData.getLine() > 5){
                        logger.info("巅峰{}门客{}的线路变成{}",getActivityId(),patronData.getPatronId(),patronData.getLine());
                        continue;
                    }
                    Map<String,List<CrossRankUnionWarWaitPatronData>> unionMap = tempLinePatronsMap.get(patronData.getLine());
                    List<CrossRankUnionWarWaitPatronData> unionPatronsMap = unionMap.get(unionData.getUnionId());
                    if(unionPatronsMap == null){
                        logger.info("巅峰活动{}比赛{},玩家商会{}，不在比赛的商会{}和{}"
                                ,getActivityId(),matchData.getGameNo(),unionData.getUnionId(),matchData.getUnionId1(),matchData.getUnionId2());
                        continue;
                    }
                    unionPatronsMap.add(patronData);
                }
            }
        }
        matchData.setReadyPatronsSortMap(tempLinePatronsMap);
    }

    //进入游戏
    public void gameInto(long serverId, long userId, RankUnionWarProto.RankUnionWarIntoGameReqMsg reqMsg) {
        RankUnionWarProto.RankUnionWarIntoGameRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarIntoGameRespMsg.newBuilder();
        respMsg.setRet(0);
        CrossRankUnionWarMatchData matchData = getGameNoMatch(reqMsg.getGameNo());
        if(matchData == null){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAME_OVER);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_GAME_INTO, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        //比赛还没开始
        if(matchData.getStatus() != 1){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_WAIT_SYNC);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_GAME_INTO, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        UnionBaseInfo unionBaseInfo = getUnionBaseInfo(matchData.getUnionId1());
        respMsg.setTeam1UnionId(matchData.getUnionId1());
        respMsg.setTeam1UnionInfo(UnionBasePb.parseUnionBaseTempMsg(unionBaseInfo));
        respMsg.setTeam2UnionId(matchData.getUnionId2());
        if(!StringUtils.isNullOrEmpty(matchData.getUnionId2())){
            UnionBaseInfo union2BaseInfo = getUnionBaseInfo(matchData.getUnionId2());
            respMsg.setTeam2UnionInfo(UnionBasePb.parseUnionBaseTempMsg(union2BaseInfo));
        }
        RankUnionWarTimeConfig timeConfig = config.getTimeConfig(matchData.getTurn());
        respMsg.setStartTime(timeConfig.getStartBattleTime());
        Map<Integer, CrossRankUnionWarLineData> lineMap = matchData.getBattleLineMap();
        for(CrossRankUnionWarLineData lineData : lineMap.values()){
            RankUnionWarProto.RankUnionWarLineMsg.Builder lineMsg = RankUnionWarProto.RankUnionWarLineMsg.newBuilder();
            lineMsg.setLine(lineData.getLine());
            lineMsg.setWinUnionId(lineData.getWinUnionId());
            lineMsg.setStartWaitTime(lineData.getUnion1StartWaitTime() == 0?lineData.getUnion2StartWaitTime():lineData.getUnion1StartWaitTime());
            lineMsg.setTeam1WaitTime(lineData.getUnion1WaitTime());
            lineMsg.setTeam2WaitTime(lineData.getUnion2WaitTime());
            Map<String, Map<Integer, CrossRankUnionWarBattlePatronData>> battleLineMap = lineData.getBattlePatronsMap();
            Map<Integer, CrossRankUnionWarBattlePatronData> battlePatronDataMap = battleLineMap.get(matchData.getUnionId1());
            //结束了数据没了客户端还要请求
            if(battlePatronDataMap != null){
                Map<Integer, CrossRankUnionWarBattlePatronData> patronsMap = new ConcurrentHashMap<>(battlePatronDataMap);
                int unionPatronDieCount = 0;
                int unionPatronMsgCount = pagePatronsNum;
                for(int i = 1;i <= patronsMap.size();i++){
                    CrossRankUnionWarBattlePatronData battlePatronData = patronsMap.get(i);
                    if(battlePatronData.isDie()){
                        unionPatronDieCount++;
                        continue;
                    }
                    RankUnionWarProto.RankUnionWarPatronMsg.Builder patronMsg = parsePatronsMsg(matchData.getUnionId1(),battlePatronData);
                    if(patronMsg == null)continue;
                    lineMsg.addTeam1Line(patronMsg);
                    unionPatronMsgCount--;
                    if(unionPatronMsgCount <= 0){
                        break;
                    }
                }
                lineMsg.addPatronsCount(patronsMap.size());
                lineMsg.addBattleCount(getLineBattlePatronsCount(matchData,lineData,matchData.getUnionId1()));
                if(!StringUtils.isNullOrEmpty(matchData.getUnionId2())){
                    Map<Integer, CrossRankUnionWarBattlePatronData> patrons2Map = battleLineMap.get(matchData.getUnionId2());
                    int union2PatronDieCount = 0;
                    int union2PatronMsgCount = pagePatronsNum;
                    for(int i = 1;i <= patrons2Map.size();i++){
                        CrossRankUnionWarBattlePatronData battlePatronData = patrons2Map.get(i);
                        if(battlePatronData.isDie()){
                            union2PatronDieCount++;
                            continue;
                        }
                        RankUnionWarProto.RankUnionWarPatronMsg.Builder patronMsg = parsePatronsMsg(matchData.getUnionId2(),battlePatronData);
                        if(patronMsg == null)continue;
                        lineMsg.addTeam2Line(patronMsg);
                        union2PatronMsgCount--;
                        if(union2PatronMsgCount <= 0){
                            break;
                        }
                    }
                    lineMsg.addPatronsCount(patrons2Map.size());
                    lineMsg.addBattleCount(getLineBattlePatronsCount(matchData,lineData,matchData.getUnionId2()));
                }
            }
            respMsg.addLines(lineMsg);
        }
        respMsg.setAttackUnionId(matchData.getAttackUnionId());
        respMsg.setMyPatronsCount(getMyPatronsCount(matchData,userId));
        //服务端保存的是历史对打时间，发下去给客户端下一次打击时间
        if(matchData.getBattleTime() == timeConfig.getStartBattleTime() || System.currentTimeMillis() < matchData.getBattleTime()){
            respMsg.setBattleTime(matchData.getBattleTime());
        }else{
            respMsg.setBattleTime(matchData.getBattleTime() + config.getBattleIntervalTime(matchData.getTurn(),matchData.getBattleTime()));
//            respMsg.setBattleTime(matchData.getBattleTime() + config.getBattleInterval() * 1000);
        }
        respMsg.setWinUnionId(matchData.getWinUnionId());
        respMsg.setTeam1Morale(matchData.getMorale1());
        respMsg.setTeam2Morale(matchData.getMorale2());
        respMsg.setIsGetLookReward(true);
        for(int line = 1;line <= 5;line ++){
            respMsg.addIsCommander(isCommander(reqMsg.getGameNo(),line,userId));
        }
        respMsg.setTurn(matchData.getTurn());
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_CROSS_GAME_INTO, respMsg);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
    }

    //获取我的门客数量
    private int getMyPatronsCount(CrossRankUnionWarMatchData matchData,long userId){
        int countUser = 0;
        //判断下玩家是不是已经被移除了
        if(!matchData.getKillRankMap().containsKey(userId)){
            return countUser;
        }
        for(CrossRankUnionWarLineData lineData : matchData.getBattleLineMap().values()){
            for(Map<Integer, CrossRankUnionWarBattlePatronData> unionWarBattlePatronDataMap : lineData.getBattlePatronsMap().values()){
                for(CrossRankUnionWarBattlePatronData patronData : unionWarBattlePatronDataMap.values()){
                    if(patronData.getUserId() == userId){
                        countUser++;
                    }
                }
            }
        }
        return countUser;
    }

    private RankUnionWarProto.RankUnionWarPatronMsg.Builder parsePatronsMsg(String unionId,CrossRankUnionWarBattlePatronData battlePatronData){
        RankUnionWarProto.RankUnionWarPatronMsg.Builder patronMsg = RankUnionWarProto.RankUnionWarPatronMsg.newBuilder();
        patronMsg.setUnionId(unionId);
        patronMsg.setUserId(battlePatronData.getUserId());
        UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(battlePatronData.getUserId());
        if(userBaseInfo == null){
            return null;
        }
        patronMsg.setNickName(userBaseInfo.getNickName());
        patronMsg.setLine(battlePatronData.getLine());
        patronMsg.setIndex(battlePatronData.getLineIndex());
        patronMsg.setPatronsNo(battlePatronData.getPatronsNo());
        patronMsg.setPatronsId(battlePatronData.getPatronId());
        patronMsg.setEarnSpeed(battlePatronData.getEarnSpeed().toString());
        patronMsg.setBool(battlePatronData.getBool().toString());
        patronMsg.setKillTime(battlePatronData.getKillTimes());
        patronMsg.setSkinId(battlePatronData.getSkinId());
        patronMsg.setPromotionId(battlePatronData.getPromotionId());
        patronMsg.setSendTime(battlePatronData.getSendTime());
        return patronMsg;
    }

    //击杀排序
    public void killRank(long serverId, long userId, RankUnionWarProto.RankUnionWarKillRankReqMsg reqMsg) {
        RankUnionWarProto.RankUnionWarKillRankRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarKillRankRespMsg.newBuilder();
        respMsg.setMyRank(0);
        respMsg.setMyKillTimes(0);
        CrossRankUnionWarMatchData matchData = getGameNoMatch(reqMsg.getGameNo());
        if(matchData != null){
            List<CrossRankUnionWarKillRankData> killRankList = matchData.getKillRankList();
            int rank = 1;
            for(CrossRankUnionWarKillRankData rankData : killRankList){
                if(rankData.getUserId() == userId){
                    respMsg.setMyRank(rank);
                    respMsg.setMyKillTimes(rankData.getKillTimes());
                }
                rank++;
                RankUnionWarProto.RankUnionWarKillRankMsg.Builder rankMsg = parseKillRankMsg(rankData);
                if(rankMsg == null){
                    continue;
                }
                respMsg.addRank(rankMsg);
            }
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_KILL_RANK_LIST, respMsg);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
    }

    private RankUnionWarProto.RankUnionWarKillRankMsg.Builder parseKillRankMsg(CrossRankUnionWarKillRankData rankData){
        RankUnionWarProto.RankUnionWarKillRankMsg.Builder rankMsg = RankUnionWarProto.RankUnionWarKillRankMsg.newBuilder();
        rankMsg.setUserId(rankData.getUserId());
        rankMsg.setKillTimes(rankData.getKillTimes());
        UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(rankData.getUserId());
        if(userBaseInfo == null){
            return null;
        }
        rankMsg.setPlayerBaseData(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
        return rankMsg;
    }

    //场景击杀日志
    public void noticeList(long serverId, long userId, RankUnionWarProto.RankUnionWarNoticeSyncReqMsg reqMsg) {
        RankUnionWarProto.RankUnionWarNoticeSyncMsg.Builder respMsg = RankUnionWarProto.RankUnionWarNoticeSyncMsg.newBuilder();
        respMsg.setActivityId(reqMsg.getActivityId());
        respMsg.setGameNo(reqMsg.getGameNo());
        CrossRankUnionWarMatchData matchData = getIngGameNoMatch(reqMsg.getGameNo());
        if(matchData != null){
            int i = 0;
            List<CrossRankUnionWarNoticeData> noticeList = new ArrayList<>(matchData.getNoticeList());
            for(int index = noticeList.size() - 1;index > 0 ;index--){
                if(i > 50)break;
                CrossRankUnionWarNoticeData noticeData = noticeList.get(index);
                UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(noticeData.getUserId());
                if(userBaseInfo == null)continue;
                RankUnionWarProto.RankUnionWarPatronsKillNoticeMsg.Builder noticeMsg = RankUnionWarProto.RankUnionWarPatronsKillNoticeMsg.newBuilder();
                noticeMsg.setNo(noticeData.getNo());
                noticeMsg.setUserId(noticeData.getUserId());
                noticeMsg.setPatronId(noticeData.getPatronId());
                noticeMsg.setKillTimes(noticeData.getKillTimes());
                noticeMsg.setTimes(noticeData.getNoticeTime());
                noticeMsg.setEnemyUnionName(getUnionData(noticeData.getEnemyUnionId()).getUnionBaseInfo().getUnionName());
                noticeMsg.setPlayerBaseData(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
                respMsg.addNotices(noticeMsg);
                i++;
            }
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_NOTICE_LIST, respMsg);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
    }

    private String getUnionId(long userId){
        if(userUnionIdMap == null || !userUnionIdMap.containsKey(userId)){
            return "";
        }
        return userUnionIdMap.get(userId);
    }

    private CrossRankUnionWarUnionData getUnionData(long userId){
        if(userUnionIdMap == null || !userUnionIdMap.containsKey(userId)){
            return null;
        }
        CrossRankUnionWarUnionData unionData = unionDataMap.get(userUnionIdMap.get(userId));
        return unionData;
    }

    private CrossRankUnionWarMemberData getUnionMember(long userId){
        if(userUnionIdMap == null || !userUnionIdMap.containsKey(userId)){
            return null;
        }
        CrossRankUnionWarUnionData unionData = unionDataMap.get(userUnionIdMap.get(userId));
        if(unionData == null){
            return null;
        }
        if(!unionData.getMemberMap().containsKey(userId)){
            return null;
        }
        return unionData.getMemberMap().get(userId);
    }

    private CrossRankUnionWarUnionData getUnionData(String unionId){
        CrossRankUnionWarUnionData unionData = unionDataMap.get(unionId);
        return unionData;
    }

    //获得自己的门客列表
    private Map<Integer, CrossRankUnionWarPatronData> getUserPatronsMap(long userId,int turn){
        CrossRankUnionWarUnionData unionData = getUnionData(userId);
        if(unionData == null){
            return null;
        }
        Map<Long, CrossRankUnionWarMemberData>  memberDataMap = unionData.getMemberMap();
        if(!memberDataMap.containsKey(userId)){
            return null;
        }
        return memberDataMap.get(userId).getPatronDataMap(turn);
    }

    //赛区信息，每个赛区多少人对战
    public void divisionInfo(long serverId, long userId, RankUnionWarProto.RankUnionWarDivisionReqMsg reqMsg) {
        int nowTurn = crossRankUnionWarData.getGameTurn();
        RankUnionWarProto.RankUnionWarDivisionRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarDivisionRespMsg.newBuilder();
        respMsg.setRet(0);
        Map<Integer, List<CrossRankUnionWarMatchData>> divisionMatchMap = turnDivisionMatchMap.get(nowTurn);
        if(divisionMatchMap != null){
            for(RankUnionWarDivisionConfig divisionConfig : config.getDivisionConfigMap().values()){
                List<CrossRankUnionWarMatchData> matchList = divisionMatchMap.get(divisionConfig.getDivision());
                int count = 0;
                if(matchList != null){
                    for(CrossRankUnionWarMatchData matchData : matchList){
                        if(StringUtils.isNullOrEmpty(matchData.getUnionId2())) {
                            count += 1;
                        }else{
                            count += 2;
                        }
                    }
                }
                RankUnionWarProto.RankUnionWarDivisionMsg.Builder divisionInfoMsg = RankUnionWarProto.RankUnionWarDivisionMsg.newBuilder();
                divisionInfoMsg.setDivision(divisionConfig.getDivision());
                divisionInfoMsg.setUnionCount(count);
                respMsg.addDivisions(divisionInfoMsg);
            }
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_DIVISION_INFO, respMsg);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
    }

    //鼓舞
    public void inspire(long serverId, long userId, RankUnionWarProto.RankUnionWarInspireReqMsg reqMsg) {
        RankUnionWarProto.CrossRankUnionWarInspireRespMsg.Builder respMsg = RankUnionWarProto.CrossRankUnionWarInspireRespMsg.newBuilder();
        respMsg.setRet(0);
        CrossRankUnionWarMatchData matchData = getIngGameNoMatch(reqMsg.getGameNo());
        if(matchData == null){
            respMsg.setCost(reqMsg.getCost());
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAME_OVER);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_INSPIRE_RES, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        //防止比赛已经开始了还在鼓舞
        synchronized (matchData){
            if(matchData.getStatus() != 0){
                respMsg.setCost(reqMsg.getCost());
                respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_MATCH_IS_GOING);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_INSPIRE_RES, respMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                return;
            }
            CrossRankUnionWarUnionData unionData = getUnionData(userId);
            if(unionData == null){
                respMsg.setCost(reqMsg.getCost());
                respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_USER_CANNOT_PLAY);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_INSPIRE_RES, respMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                return;
            }
            int userInspireTimes = matchData.getUserInspireTimesMap().getOrDefault(userId,0);
            String cost = GameConfig.GAME_MONEY_INGOTS + "=" +config.getInspireCost(userInspireTimes);
            if(reqMsg.hasCost()){
                if(!cost.equals(reqMsg.getCost())){
                    respMsg.setCost(reqMsg.getCost());
                    respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_INSPIRE_COST_ERR);
                    YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_INSPIRE_RES, respMsg);
                    CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                    return;
                }
                matchData.getUserInspireTimesMap().put(userId,userInspireTimes + 1);
                if(matchData.getUnionId1().equals(unionData.getUnionId())){
                    matchData.addMorale1();
                }else{
                    matchData.addMorale2();
                }
                addNeedUpdateMatch(matchData);
                respMsg.setCost(cost);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_INSPIRE_RES, respMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            }else{
                RankUnionWarProto.RankUnionWarInspireReqMsg.Builder reqServerMsg = reqMsg.toBuilder();
                reqServerMsg.setCost(cost);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_INSPIRE, reqServerMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            }
        }
    }


    //领取观战奖励
    public void getLookReward(long serverId, long userId, RankUnionWarProto.RankUnionWarGetLookRewardReqMsg reqMsg) {
        RankUnionWarProto.RankUnionWarGetLookRewardRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarGetLookRewardRespMsg.newBuilder();
        respMsg.setRet(0);
        CrossRankUnionWarMatchData matchData = getIngGameNoMatch(reqMsg.getGameNo());
        if(matchData == null){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAME_OVER);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_GET_LOOK_REWARD, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        respMsg.setTurn(matchData.getTurn());
        synchronized (getUserLock(userId)){
            /*if(matchData.getLookRewardList().contains(userId)){
                respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_IS_GET_LOOK_REWARD);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_GET_LOOK_REWARD, respMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                return;
            }*/
//            matchData.getLookRewardList().add(userId);
//            addNeedUpdateMatch(matchData);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_CROSS_GET_LOOK_REWARD, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
        }
    }

    //获取赛区详情，对应看某个赛区的
    public void teamDetailList(long serverId, long userId, RankUnionWarProto.RankUnionWarTeamMatchListReqMsg reqMsg) {
        int nowTurn = crossRankUnionWarData.getGameTurn();
        RankUnionWarProto.RankUnionWarTeamMatchListRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarTeamMatchListRespMsg.newBuilder();
        respMsg.setRet(0);
        if(nowTurn != 0){
            List<CrossRankUnionWarMatchData> turnMatchList = turnDivisionMatchMap.get(nowTurn).get(reqMsg.getDivision());
            if(turnMatchList != null){
                for(CrossRankUnionWarMatchData matchData : turnMatchList){
                    respMsg.addMatches(parseMatchDetailMsg(matchData,userId));
                }
            }
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_TEAM_MATH_LIST, respMsg);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
    }


    //竞猜的所有数据列表
    public void gambleList(long serverId, long userId, RankUnionWarProto.RankUnionWarGambleListReqMsg reqMsg) {
        RankUnionWarProto.RankUnionWarGambleListRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarGambleListRespMsg.newBuilder();
        respMsg.setRet(0);
        for(int turn : gambleMap.keySet()){
            CrossRankUnionWarGambleData gambleData = gambleMap.get(turn);
            RankUnionWarProto.RankUnionWarGambleMsg.Builder turnMsg = RankUnionWarProto.RankUnionWarGambleMsg.newBuilder();
            turnMsg.setTurn(turn);
            turnMsg.setRightTimes(-1);
            List<String> winUnionIdList = gambleData.getWinUnionIdList();
            int count = 0;
            if(winUnionIdList!= null && winUnionIdList.size() != 0){
                Map<Long, Map<Integer,String>> guessMap = gambleData.getGuessUnionIdMap();
                if(guessMap.containsKey(userId)){
                    for(String unionId : guessMap.get(userId).values()){
                        if(winUnionIdList.contains(unionId)){
                            count++;
                        }
                    }
                }
            }
            turnMsg.setRightTimes(count);
            for(int gameNo : gambleData.getGameNoMap().keySet()){
                CrossRankUnionWarMatchData matchData = getGameNoMatch(gameNo);
                if(matchData == null)continue;
                turnMsg.addMatches(parseMatchDetailMsg(matchData,userId));
            }
            respMsg.addTurns(turnMsg);
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_GAMBLE_LIST, respMsg);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
    }

    //竞猜押注
    public void gambleStake(long serverId, long userId, RankUnionWarProto.RankUnionWarGambleStakeReqMsg reqMsg) {
        RankUnionWarProto.RankUnionWarGambleStakeRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarGambleStakeRespMsg.newBuilder();
        respMsg.setRet(0);

        CrossRankUnionWarMatchData matchData = getIngGameNoMatch(reqMsg.getGameNo());
        if(matchData == null){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAME_OVER);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_GAMBLE_STAKE, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        //比赛已经开始了还能押注
        synchronized (matchData){
            if(matchData.getStatus() != 0){
                respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_MATCH_IS_GOING);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_GAMBLE_STAKE, respMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                return;
            }
            int turn = matchData.getTurn();
            CrossRankUnionWarGambleData gambleData = gambleMap.get(turn);
            if(!gambleData.getGameNoMap().containsKey(reqMsg.getGameNo())){
                respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_NOT_GAMBLE_UNION);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_GAMBLE_STAKE, respMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                return;
            }
            List<String> unionIdList = gambleData.getGameNoMap().get(reqMsg.getGameNo());
            if(!unionIdList.contains(reqMsg.getUnionId())){
                respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAMBLE_GAME_UNION_ERR);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_GAMBLE_STAKE, respMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                return;
            }
            Map<Long, Map<Integer,String>> userGuessMap = gambleData.getGuessUnionIdMap();
            if(!userGuessMap.containsKey(userId)){
                userGuessMap.put(userId,new ConcurrentHashMap<>());
            }
            Map<Integer,String> gussUnionIdMap = userGuessMap.get(userId);
            if(gussUnionIdMap.containsKey(reqMsg.getGameNo())){
                respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAMBLE_STAKE_UNION);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_GAMBLE_STAKE, respMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                return;
            }
            if(matchData.getUnionId1().equals(reqMsg.getUnionId())){
                matchData.addUnion1Support();
            }else{
                matchData.addUnion2Support();
            }
            gussUnionIdMap.put(reqMsg.getGameNo(),reqMsg.getUnionId());

            addNeedUpdateGamble(gambleData);
            addNeedUpdateMatch(matchData);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_GAMBLE_STAKE, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
        }
    }

    //查看比赛对应商会胜利几条线路
    private int getWinMatchTimes(CrossRankUnionWarMatchData matchData,String unionId){
        if(StringUtils.isNullOrEmpty(unionId))return 0;
        int winCount = 0;
        for(CrossRankUnionWarLineData line : matchData.getBattleLineMap().values()){
            if(unionId.equals(line.getWinUnionId())){
                winCount++;
            }
        }
        return winCount;
    }

    //查看比赛对应商会失败几条线路
    private int getLoseMatchTimes(CrossRankUnionWarMatchData matchData,String unionId){
        int loseCount = 0;
        String eUnionId = matchData.getUnionId1();
        if(matchData.getUnionId1().equals(unionId)){
            eUnionId = matchData.getUnionId2();
        }
        for(CrossRankUnionWarLineData line : matchData.getBattleLineMap().values()){
            if(eUnionId.equals(line.getWinUnionId())){
                loseCount++;
            }
        }
        return loseCount;
    }

    //战况，只有涉及到自己商会的战斗才会出现
    public void matchResultList(long serverId, long userId,RankUnionWarProto.RankUnionWarmMatchResultReqMsg reqMsg) {
        RankUnionWarProto.RankUnionWarmMatchResultRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarmMatchResultRespMsg.newBuilder();
        String lookUnionId = reqMsg.getUnionId();
        CrossRankUnionWarUnionData unionData = getUnionData(lookUnionId);
        respMsg.setUnionId(lookUnionId);
        if(unionData != null){
            respMsg.setUnionInfo(UnionBasePb.parseUnionBaseTempMsg(getUnionBaseInfo(lookUnionId)));
            for(CrossRankUnionWarMatchData matchData : battleMatchMap.values()){
                if((matchData.getUnionId1().equals(unionData.getUnionId()) || matchData.getUnionId2().equals(unionData.getUnionId()))
                        && !StringUtils.isNullOrEmpty(matchData.getWinUnionId())){
                    RankUnionWarProto.RankUnionWarSelfMatchMsg.Builder matchMsg = RankUnionWarProto.RankUnionWarSelfMatchMsg.newBuilder();
                    matchMsg.setTurn(matchData.getTurn());
                    matchMsg.setGameNo(matchData.getGameNo());
                    matchMsg.setGameType(matchData.getDivision());
                    matchMsg.setWinTimes(getWinMatchTimes(matchData,unionData.getUnionId()));
                    matchMsg.setLoseTimes(getLoseMatchTimes(matchData,unionData.getUnionId()));
                    matchMsg.setIsGetReward(matchData.getMatchRewardList().contains(userId)?1:0);
                    matchMsg.setNo(matchData.getNo());
                    String eUnionId = matchData.getUnionId1();
                    if(matchData.getUnionId1().equals(unionData.getUnionId())){
                        eUnionId = matchData.getUnionId2();
                    }
                    matchMsg.setUnionId(eUnionId);
                    matchMsg.setWinUnionId(matchData.getWinUnionId());
                    if(!StringUtils.isNullOrEmpty(eUnionId)){
                        matchMsg.setUnionInfo(UnionBasePb.parseUnionBaseTempMsg(getUnionBaseInfo(eUnionId)));
                    }
                    respMsg.addMatches(matchMsg);
                }
            }
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_MATCH_RESULT, respMsg);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
    }


    //查看战报
    public void matchInfo(long serverId, long userId, RankUnionWarProto.RankUnionWarMatchInfoReqMsg reqMsg) {
        RankUnionWarProto.RankUnionWarMatchInfoRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarMatchInfoRespMsg.newBuilder();
        respMsg.setRet(0);
        CrossRankUnionWarMatchData matchData = getGameNoMatch(reqMsg.getGameNo());
        if(matchData == null || StringUtils.isNullOrEmpty(matchData.getWinUnionId())){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_MATCH_NOT_OVER);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_MATCH_INFO, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        RankUnionWarProto.RankUnionWarTeamMatchInfoMsg.Builder matchInfoMsg = RankUnionWarProto.RankUnionWarTeamMatchInfoMsg.newBuilder();
        matchInfoMsg.setGameNo(matchData.getGameNo());
        matchInfoMsg.setGameType(matchData.getDivision());
        matchInfoMsg.setTurn(matchData.getTurn());
        matchInfoMsg.setTeam1UnionId(matchData.getUnionId1());
        matchInfoMsg.setTeam2UnionId(matchData.getUnionId2());
        matchInfoMsg.setNo(matchData.getNo());
        matchInfoMsg.setTeam1UnionInfo(UnionBasePb.parseUnionBaseTempMsg(getUnionBaseInfo(matchData.getUnionId1())));
        if(!StringUtils.isNullOrEmpty(matchData.getUnionId2())){
            matchInfoMsg.setTeam2UnionInfo(UnionBasePb.parseUnionBaseTempMsg(getUnionBaseInfo(matchData.getUnionId2())));
        }
        matchInfoMsg.setWinUnionId(matchData.getWinUnionId());
        for(CrossRankUnionWarLineData line : matchData.getBattleLineMap().values()){
            matchInfoMsg.addLineWinner(line.getWinUnionId());
        }
        Map<Long, CrossRankUnionWarKillRankData> userRankMap = matchData.getKillRankMap();
        CrossRankUnionWarUnionData unionData = getUnionData(matchData.getUnionId1());
        for(long memberUserId : unionData.getMemberMap().keySet()){
            if(userRankMap.containsKey(memberUserId)){
                RankUnionWarProto.RankUnionWarKillRankMsg.Builder rankMsg = parseKillRankMsg(userRankMap.get(memberUserId));
                if(rankMsg != null){
                    matchInfoMsg.addMember1(rankMsg);
                }
            }
        }
        if(!StringUtils.isNullOrEmpty(matchData.getUnionId2())){
            CrossRankUnionWarUnionData union2Data = getUnionData(matchData.getUnionId2());
            for(long memberUserId : union2Data.getMemberMap().keySet()){
                if(userRankMap.containsKey(memberUserId)){
                    RankUnionWarProto.RankUnionWarKillRankMsg.Builder rankMsg = parseKillRankMsg(userRankMap.get(memberUserId));
                    if(rankMsg != null){
                        matchInfoMsg.addMember2(rankMsg);
                    }
                }
            }
        }
        respMsg.setInfos(matchInfoMsg);
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_MATCH_INFO, respMsg);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
    }

    //领取每一局比赛奖励
    public void getMatchReward(long serverId, long userId, RankUnionWarProto.RankUnionWarGetMatchRewardReqMsg reqMsg) {
        RankUnionWarProto.RankUnionWarGetMatchRewardRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarGetMatchRewardRespMsg.newBuilder();
        respMsg.setRet(0);
        CrossRankUnionWarMatchData matchData = getGameNoMatch(reqMsg.getGameNo());
        if(matchData == null || StringUtils.isNullOrEmpty(matchData.getWinUnionId())){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_MATCH_NOT_OVER);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_GET_MATCH_REWARD, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        synchronized (getUserLock(userId)){
            CrossRankUnionWarUnionData unionData = getUnionData(userId);
            if(unionData == null){
                respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_USER_CANNOT_PLAY);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_GET_MATCH_REWARD, respMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                return;
            }
            if(!unionData.getMemberMap().containsKey(userId)){
                respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_USER_CANNOT_PLAY);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_GET_MATCH_REWARD, respMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                return;
            }
            if(!unionData.getUnionId().equals(matchData.getUnionId1()) && !unionData.getUnionId().equals(matchData.getUnionId2())){
                respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GET_MATCH_REWARD_NOT_SELF);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_GET_MATCH_REWARD, respMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                return;
            }
            List<Long> getMatchRewardList = matchData.getMatchRewardList();
            if(getMatchRewardList.contains(userId)){
                respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_IS_GET_MATCH_REWARD);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_GET_MATCH_REWARD, respMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                return;
            }
            getMatchRewardList.add(userId);
            matchData.setMatchRewardList(getMatchRewardList);
            addNeedUpdateMatch(matchData);
            RankUnionWarDivisionConfig divisionConfig = config.getDivisionConfig(matchData.getDivision());
            String reward = "";
            if(isCommander(matchData.getGameNo(),userId)){
                reward = divisionConfig.getRewardsPresidentList().get(unionData.getUnionId().equals(matchData.getWinUnionId())?0:1);
            }else{
                reward = divisionConfig.getRewardsMemberList().get(unionData.getUnionId().equals(matchData.getWinUnionId())?0:1);
            }
            RankUnionWarProto.CrossRankUnionWarMatchRewardRespMsg.Builder respServerMsg = RankUnionWarProto.CrossRankUnionWarMatchRewardRespMsg.newBuilder();
            respServerMsg.setRet(0);
            respServerMsg.setReward(reward);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_CROSS_GET_MATCH_REWARD, respServerMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
        }
    }

    //捐献详情
    public void donateInfo(long serverId, long userId, RankUnionWarProto.RankUnionWarDonateInfoReqMsg reqMsg) {
        RankUnionWarProto.RankUnionWarDonateInfoRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarDonateInfoRespMsg.newBuilder();
        respMsg.setRet(0);
        CrossRankUnionWarUnionData unionData = getUnionData(userId);
        if(unionData == null){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_USER_CANNOT_PLAY);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_DONATE_INFO, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        for(CrossRankUnionWarMemberData memberData: unionData.getMemberMap().values()){
            RankUnionWarProto.RankUnionWarUserDonateInfoMsg.Builder mMsg = RankUnionWarProto.RankUnionWarUserDonateInfoMsg.newBuilder();
            mMsg.setUserId(memberData.getUserId());
            UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(memberData.getUserId());
            if(userBaseInfo == null){
                continue;
            }
            mMsg.setNickName(userBaseInfo.getNickName());
            mMsg.setCount(memberData.getDonateNum());
            respMsg.addDonates(mMsg);
        }
        respMsg.setDonateNum(unionData.getDonateNum());
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_DONATE_INFO, respMsg);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
    }

    //捐献
    public void donate(long serverId, long userId, RankUnionWarProto.RankUnionWarDonateReqMsg reqMsg) {
        RankUnionWarProto.RankUnionWarDonateRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarDonateRespMsg.newBuilder();
        respMsg.setRet(0);
        int donateNum = reqMsg.getNum();
        //把数量赋值返回预扣除的
        respMsg.setReward(String.valueOf(donateNum));
        CrossRankUnionWarUnionData unionData = getUnionData(userId);
        if(unionData == null){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_DONATE_ERR);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_CROSS_DONATE, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        synchronized (unionData){
            if(!unionData.getMemberMap().containsKey(userId)){
                respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_DONATE_ERR);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_CROSS_DONATE, respMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                return;
            }
            CrossRankUnionWarMemberData memberData = unionData.getMemberMap().get(userId);
            memberData.setDonateNum(memberData.getDonateNum() + donateNum);
            unionData.setDonateNum(unionData.getDonateNum() + donateNum);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_RANKUNIONWAR_CROSS_DONATE, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
        }
    }


    public void printTask() {
//        getLogger().error("【定时打任务】 - {}", JSON.toJSONString("aaa"));
    }

    //指挥官信息
    public void commanderInfo(long serverId, long userId, RankUnionWarProto.RankUnionWarCommanderInfoReqMsg reqMsg) {
        RankUnionWarProto.RankUnionWarCommanderInfoRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarCommanderInfoRespMsg.newBuilder();
        respMsg.setRet(0);
        CrossRankUnionWarMatchData matchData = getIngGameNoMatch(reqMsg.getGameNo());
        if(matchData == null){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAME_OVER);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_COMMANDER_INFO, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        CrossRankUnionWarUnionData unionData = getUnionData(userId);
        if(unionData == null){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_USER_CANNOT_PLAY);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_COMMANDER_INFO, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        /*CrossRankUnionWarMemberData memberData = unionData.getMemberMap().get(userId);
        //所有人都能看
        if(memberData == null || (memberData.getPosition() != eUnionPosition.Master.getValue() && memberData.getPosition() != eUnionPosition.DeputyMaster.getValue())){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_APPOINT_COMMANDER_ERR);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_COMMANDER_INFO, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }*/
        Map<Integer,Integer> patronsCountMap = new ConcurrentHashMap<>();
        Map<Integer,BigInteger> earnSpeedMap = new ConcurrentHashMap<>();
        for(int i = 1; i <= 5; i++){
            patronsCountMap.put(i,0);
            earnSpeedMap.put(i,BigInteger.ZERO);
        }
        Map<Long, Map<Integer, CrossRankUnionWarWaitPatronData>> waitPatronsMap = matchData.getWaitPatronsMap();
        for(CrossRankUnionWarMemberData memberData : unionData.getMemberMap().values()){
            if(!waitPatronsMap.containsKey(memberData.getUserId()))continue;
            for(CrossRankUnionWarWaitPatronData waitPatronData : waitPatronsMap.get(memberData.getUserId()).values()){
                if(waitPatronData.getLine() != 0){
                    int line = waitPatronData.getLine();
                    patronsCountMap.put(line,patronsCountMap.get(line) + 1);
                    earnSpeedMap.put(line,earnSpeedMap.get(line).add(waitPatronData.getEarnSpeed()));
                }
            }
        }
        for(int i = 1; i <= 5; i++){
            respMsg.addPatronsCount(patronsCountMap.get(i));
            respMsg.addEarnSpeed(earnSpeedMap.get(i).toString());
        }
        Map<Integer,List<Long>> lineUserIdMap = unionData.getOpUserIdMap().get(matchData.getGameNo());
        if(lineUserIdMap == null){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_APPOINT_COMMANDER_ERR);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_COMMANDER_INFO, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        for(int line : lineUserIdMap.keySet()){
            for(long opUserId : lineUserIdMap.get(line)){
                CrossRankUnionWarMemberData memberInfo = unionData.getMemberMap().get(opUserId);
                if(memberInfo.getPosition() == eUnionPosition.Master.getValue() || memberInfo.getPosition() == eUnionPosition.DeputyMaster.getValue())continue;
                RankUnionWarProto.RankUnionWarCommanderInfoMsg.Builder opUserMsg = RankUnionWarProto.RankUnionWarCommanderInfoMsg.newBuilder();
                opUserMsg.setLine(line);
                opUserMsg.setUserId(opUserId);
                respMsg.addCommander(opUserMsg);
            }
        }
        for(CrossRankUnionWarMemberData memberData : unionData.getMemberMap().values()){
            if(memberData.getPosition() == eUnionPosition.Master.getValue() || memberData.getPosition() == eUnionPosition.DeputyMaster.getValue())continue;
            if(!memberData.isQuit()){
                respMsg.addMemberUserId(memberData.getUserId());
            }
        }
        if(unionData.getUnionId().equals(matchData.getUnionId1())){
            respMsg.setFlagColor(0);
        }else{
            respMsg.setFlagColor(1);
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_COMMANDER_INFO, respMsg);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
    }

    //任命指导员
    public void appointCommander(long serverId, long userId, RankUnionWarProto.RankUnionWarAppointCommanderReqMsg reqMsg) {
        RankUnionWarProto.RankUnionWarAppointCommanderRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarAppointCommanderRespMsg.newBuilder();
        respMsg.setRet(0);
        CrossRankUnionWarMatchData matchData = getIngGameNoMatch(reqMsg.getGameNo());
        if(matchData == null || matchData.getStatus() != 0){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAME_NOT_PREPARE);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_APPOINT_COMMANDER, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        CrossRankUnionWarUnionData unionData = getUnionData(userId);
        if(unionData == null){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_USER_CANNOT_PLAY);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_APPOINT_COMMANDER, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        for(long commandUserId : reqMsg.getUserIdList()){
            if(!unionData.getMemberMap().containsKey(commandUserId) || unionData.getMemberMap().get(commandUserId).isQuit()){
                respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_APPOINT_NOT_MATCH_MEMBER);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_APPOINT_COMMANDER, respMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                return;
            }
        }
        if(!unionData.getOpUserIdMap().containsKey(matchData.getGameNo())){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_APPOINT_COMMANDER_ERR);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_APPOINT_COMMANDER, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        CrossRankUnionWarMemberData unionWarMemberData = unionData.getMemberMap().get(userId);
        if(unionWarMemberData == null ||
                (unionWarMemberData.getPosition() != eUnionPosition.Master.getValue() && unionWarMemberData.getPosition() != eUnionPosition.DeputyMaster.getValue())){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_APPOINT_COMMANDER_ERR);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_APPOINT_COMMANDER, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        synchronized (unionData){
            logger.info("巅峰{}活动玩家{}任命{}为指导员",getActivityId(),userId,reqMsg.getUserIdList().toString());
            Map<Integer, Map<Integer, List<Long>>> opGameUserIdMap = unionData.getOpUserIdMap();
            Map<Integer,List<Long>> lineUserIdMap = opGameUserIdMap.get(matchData.getGameNo());
            List<Long> oUserIdList = new ArrayList<>(lineUserIdMap.get(reqMsg.getLine()));
            lineUserIdMap.put(reqMsg.getLine(),new ArrayList<>(reqMsg.getUserIdList()));
            unionData.setOpUserIdMap(opGameUserIdMap);
            for(long appointCommanderUserId : reqMsg.getUserIdList()){
                List<Long> userIdList = new ArrayList<>();
                if(!oUserIdList.contains(appointCommanderUserId)){
                    userIdList.add(appointCommanderUserId);
                }
                if(userIdList.size() > 0){
                    RankUnionWarProto.CrossRankUnionWarAppointCommanderReqMsg.Builder builder = RankUnionWarProto.CrossRankUnionWarAppointCommanderReqMsg.newBuilder();
                    builder.setActivityId(getActivityId());
                    List<Long> serverIdList = config.getActivityInfo().getServerIdList();
                    builder.setUnionId(unionData.getUnionId());
                    builder.setUserId(userId);
                    builder.setLine(reqMsg.getLine());
                    builder.addAllCommanderUserId(userIdList);
                    CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverIdList.get(randomHelper.next(0,serverIdList.size())), 0, YanQuMessageUtils.buildMessage(CrossProtocol.C3_CROSS_RANKUNIONWAR_APPOINT_COMMANDER, builder));
                }
            }
        }

        CrossAutoLogMgr.add(new CrossRankUnionWarCommandLog(
                getActivityId(), reqMsg.getGameNo(), unionData.getUnionId(), userId, unionWarMemberData.getPosition(), reqMsg.getLine()
                , StringUtils.listToString(reqMsg.getUserIdList(), ",")));

        Map<Integer,Integer> patronsCountMap = new ConcurrentHashMap<>();
        Map<Integer,BigInteger> earnSpeedMap = new ConcurrentHashMap<>();
        for(int i = 1; i <= 5; i++){
            patronsCountMap.put(i,0);
            earnSpeedMap.put(i,BigInteger.ZERO);
        }
        Map<Long, Map<Integer, CrossRankUnionWarWaitPatronData>> waitPatronsMap = new ConcurrentHashMap<>(matchData.getWaitPatronsMap());
        for(CrossRankUnionWarMemberData memberData : unionData.getMemberMap().values()){
            if(waitPatronsMap.containsKey(memberData.getUserId())){
                for(CrossRankUnionWarWaitPatronData waitPatronData : waitPatronsMap.get(memberData.getUserId()).values()){
                    if(waitPatronData.getLine() != 0){
                        int line = waitPatronData.getLine();
                        patronsCountMap.put(line,patronsCountMap.get(line) + 1);
                        earnSpeedMap.put(line,earnSpeedMap.get(line).add(waitPatronData.getEarnSpeed()));
                    }
                }
            }
        }
        for(int i = 1; i <= 5; i++){
            respMsg.addPatronsCount(patronsCountMap.get(i));
            respMsg.addEarnSpeed(earnSpeedMap.get(i).toString());
        }
        Map<Integer,List<Long>> lineUserIdMap = unionData.getOpUserIdMap().get(matchData.getGameNo());
        for(int line : lineUserIdMap.keySet()){
            for(long opUserId : lineUserIdMap.get(line)){
                RankUnionWarProto.RankUnionWarCommanderInfoMsg.Builder opUserMsg = RankUnionWarProto.RankUnionWarCommanderInfoMsg.newBuilder();
                opUserMsg.setLine(line);
                opUserMsg.setUserId(opUserId);
                respMsg.addCommander(opUserMsg);
            }
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_APPOINT_COMMANDER, respMsg);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
    }


    //计算线路门客总线路
    private BigInteger getLinePatronsTotalBool(CrossRankUnionWarLineData lineData,String unionId){
        BigInteger earnSpeed = BigInteger.ZERO;
        //门客计算过了死亡复活了不在重复计算
        Map<Long,List<Integer>> usePatronsMap = new ConcurrentHashMap<>();
        CrossRankUnionWarUnionData unionData = getUnionData(unionId);
        Map<Integer,CrossRankUnionWarBattlePatronData> battlePatronDataMap = lineData.getBattlePatronsMap().get(unionId);
        for(CrossRankUnionWarBattlePatronData patrons : battlePatronDataMap.values()){
            if(!patrons.isDie()){
                earnSpeed = earnSpeed.add(patrons.getBool());
                if(!usePatronsMap.containsKey(patrons.getUserId())){
                    usePatronsMap.put(patrons.getUserId(),new ArrayList<>());
                }
                if(!usePatronsMap.get(patrons.getUserId()).contains(patrons.getPatronId())){
                    CrossRankUnionWarWaitPatronData waitPatronData = getWaitPatrons(lineData.getGameNo(),patrons.getUserId(),patrons.getPatronId());
                    if(waitPatronData != null){
                        int battleTime = getPatronsReviveTimes(waitPatronData) - getPatronsDieTimes(waitPatronData);
                        earnSpeed = earnSpeed.add(waitPatronData.getEarnSpeed().multiply(BigInteger.valueOf(battleTime)));
                    }
                    usePatronsMap.get(patrons.getUserId()).add(patrons.getPatronId());
                }
            }
        }
        return  earnSpeed;
    }

    //判断用户是不是一场比赛某一条线的操作员
    private boolean isCommander(int gameNo,int line,long userId){
        CrossRankUnionWarUnionData unionData = getUnionData(userId);
        if(unionData == null){
            return false;
        }
        CrossRankUnionWarMatchData match = getIngGameNoMatch(gameNo);
        if(match != null && match.getStatus() == 0 && unionData.getMemberMap().containsKey(userId)){
            int position = unionData.getMemberMap().get(userId).getPosition();
            if(position == eUnionPosition.Master.getValue() || position == eUnionPosition.DeputyMaster.getValue()){
                return true;
            }
        }
        if(!unionData.getOpUserIdMap().containsKey(gameNo)){
            return false;
        }
        if(!unionData.getOpUserIdMap().get(gameNo).containsKey(line)){
            return false;
        }
        if(!unionData.getOpUserIdMap().get(gameNo).get(line).contains(userId)){
            return false;
        }
        return true;
    }

    //是不是指挥官
    private boolean isCommander(int gameNo,long userId){
        CrossRankUnionWarUnionData unionData = getUnionData(userId);
        if(unionData == null){
            return false;
        }
        if(!unionData.getOpUserIdMap().containsKey(gameNo)){
            return false;
        }
        for(List<Long> userIdList : unionData.getOpUserIdMap().get(gameNo).values()){
            if(userIdList.contains(userId)){
                return true;
            }
        }
        return false;
    }

    //门客战死多少次了
    private int getPatronsDieTimes(CrossRankUnionWarWaitPatronData patronData){
        int count = 0;
        CrossRankUnionWarMatchData matchData = getGameNoMatch(patronData.getGameNo());
        CrossRankUnionWarUnionData unionData = getUnionData(patronData.getUserId());
        if(matchData == null || unionData == null){
            logger.info("巅峰{}计算门客死亡次数没有找到对应商会gameNo:{},userId:{}",getActivityId(),patronData.getGameNo(),patronData.getUserId());
            return count;
        }
        CrossRankUnionWarLineData lineData = matchData.getBattleLineMap().get(patronData.getLine());
        for(CrossRankUnionWarBattlePatronData battlePatronData : lineData.getBattlePatronsMap().get(unionData.getUnionId()).values()){
            if(patronData.getUserId() == battlePatronData.getUserId() && battlePatronData.getPatronId() == patronData.getPatronId() && battlePatronData.isDie()){
                count++;
            }
        }
        return count;
    }

    //门客复活了多次了
    private int getPatronsReviveTimes(CrossRankUnionWarWaitPatronData waitPatronData){
        int count = 0;
        CrossRankUnionWarMatchData matchData = getGameNoMatch(waitPatronData.getGameNo());
        if(matchData == null){
            return count;
        }
        CrossRankUnionWarPatronData patronData = getPatronsInfo(waitPatronData.getUserId(),matchData.getTurn(),waitPatronData.getPatronId());
        if(patronData == null){
            return count;
        }
        return patronData.getBuyMap().getOrDefault(waitPatronData.getGameNo(),0);
    }

    //复活门客信息
    public void reviveInfo(long serverId, long userId, RankUnionWarProto.RankUnionWarPatronsReviveInfoReqMsg reqMsg) {
        RankUnionWarProto.RankUnionWarPatronsReviveInfoRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarPatronsReviveInfoRespMsg.newBuilder();
        respMsg.setRet(0);
        CrossRankUnionWarMatchData matchData = getIngGameNoMatch(reqMsg.getGameNo());
        if(matchData == null){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAME_OVER);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_REVIVE_INFO, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        CrossRankUnionWarUnionData unionData = getUnionData(userId);
        if(unionData == null){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAME_NOT_COMMANDER);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_REVIVE_INFO, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        /*if(!unionData.getOpUserIdMap().containsKey(reqMsg.getGameNo())
                ||!unionData.getOpUserIdMap().get(reqMsg.getGameNo()).containsKey(reqMsg.getLine())
                ||!unionData.getOpUserIdMap().get(reqMsg.getGameNo()).get(reqMsg.getLine()).contains(userId)){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAME_NOT_COMMANDER);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_REVIVE_INFO, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }*/
        Map<Integer,CrossRankUnionWarWaitPatronData> indexWaitPatronsList = new ConcurrentHashMap<>();
        for(CrossRankUnionWarMemberData memberData : unionData.getMemberMap().values()){
            Map<Long, Map<Integer, CrossRankUnionWarWaitPatronData>> waitPatronsMap = new ConcurrentHashMap<>(matchData.getWaitPatronsMap());
            if(!waitPatronsMap.containsKey(memberData.getUserId()))continue;
            UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(memberData.getUserId());
            if(userBaseInfo == null){
                continue;
            }
            for(CrossRankUnionWarWaitPatronData waitPatronData : waitPatronsMap.get(memberData.getUserId()).values()){
                if(waitPatronData.getLine() != reqMsg.getLine())continue;
                indexWaitPatronsList.put(waitPatronData.getLineIndex(),waitPatronData);
            }
        }
        for(int i = 1;i <= indexWaitPatronsList.size();i++){
            CrossRankUnionWarWaitPatronData waitPatronData = indexWaitPatronsList.get(i);
            UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(waitPatronData.getUserId());
            CrossRankUnionWarMemberData memberData = unionData.getMemberMap().get(waitPatronData.getUserId());
            RankUnionWarProto.RankUnionWarRevivePatronsInfoMsg.Builder patronsMsg = RankUnionWarProto.RankUnionWarRevivePatronsInfoMsg.newBuilder();
            patronsMsg.setUserId(waitPatronData.getUserId());
            patronsMsg.setNickName(userBaseInfo.getNickName());
            patronsMsg.setPatronsId(waitPatronData.getPatronId());
            patronsMsg.setEarnSpeed(waitPatronData.getEarnSpeed().toString());
            patronsMsg.setSkinId(waitPatronData.getSkinId());
            patronsMsg.setPromotionId(waitPatronData.getPromotionId());
            patronsMsg.setLine(waitPatronData.getLine());
            patronsMsg.setReviveTimes(memberData.getPatronDataMap(matchData.getTurn()).get(waitPatronData.getPatronId()).getBuyMap().getOrDefault(reqMsg.getGameNo(),0));
            patronsMsg.setDieTimes(getPatronsDieTimes(waitPatronData));
            respMsg.addPatron(patronsMsg);
        }
        CrossRankUnionWarLineData lineData = matchData.getBattleLineMap().get(reqMsg.getLine());
        Map<Integer, CrossRankUnionWarBattlePatronData> battlePatronDataMap = lineData.getBattlePatronsMap().get(unionData.getUnionId());
        respMsg.setEarnSpeed(getLinePatronsTotalBool(lineData,unionData.getUnionId()).toString());
        respMsg.setPatronsCount(respMsg.getPatronCount());
        respMsg.setItems(unionData.getDonateNum());
        respMsg.setIsCommander(isCommander(reqMsg.getGameNo(),reqMsg.getLine(),userId));
        respMsg.setBattleTime(matchData.getBattleTime());
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_REVIVE_INFO, respMsg);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
    }

    //复活门客
    public void revive(long serverId, long userId, RankUnionWarProto.RankUnionWarRevivePatronsReqMsg reqMsg) {
        RankUnionWarProto.RankUnionWarRevivePatronsRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarRevivePatronsRespMsg.newBuilder();
        respMsg.setRet(0);
        CrossRankUnionWarMatchData matchData = getIngGameNoMatch(reqMsg.getGameNo());
        if(matchData == null || matchData.getStatus() != 1){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAME_OVER);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_REVIVE, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        CrossRankUnionWarLineData lineData = matchData.getBattleLineMap().get(reqMsg.getLine());
        if(!StringUtils.isNullOrEmpty(lineData.getWinUnionId())){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_MATCH_LINE_OVER);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_REVIVE, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        CrossRankUnionWarUnionData unionData = getUnionData(userId);
        if(unionData == null){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAME_NOT_COMMANDER);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_REVIVE, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        if(!unionData.getOpUserIdMap().containsKey(reqMsg.getGameNo()) ||
                !unionData.getOpUserIdMap().get(reqMsg.getGameNo()).containsKey(reqMsg.getLine()) ||
                !unionData.getOpUserIdMap().get(reqMsg.getGameNo()).get(reqMsg.getLine()).contains(userId)){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAME_NOT_COMMANDER);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_REVIVE, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        //同一个商会的人在复活门客加锁，不能并发，初始化比赛中的加门客已经改好状态，添加门客进入比赛是线性的，只会死亡和复活相等才复活
        synchronized (matchData){
            int costReviveCount = 0;
            Map<Long, Map<Integer, CrossRankUnionWarWaitPatronData>> waitPatronsMap = new ConcurrentHashMap<>(matchData.getWaitPatronsMap());
            for(RankUnionWarProto.RankUnionWarPatronsInfoSimpleMsg patronsInfoSimpleMsg : reqMsg.getPatronsInfosList()){
                if(!waitPatronsMap.containsKey(patronsInfoSimpleMsg.getUserId())){
                    respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAME_REVIVE_ERR);
                    YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_REVIVE, respMsg);
                    CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                    return;
                }
                if(!waitPatronsMap.get(patronsInfoSimpleMsg.getUserId()).containsKey(patronsInfoSimpleMsg.getPatronsId())){
                    respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAME_REVIVE_ERR);
                    YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_REVIVE, respMsg);
                    CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                    return;
                }
                CrossRankUnionWarWaitPatronData waitPatronData = waitPatronsMap.get(patronsInfoSimpleMsg.getUserId()).get(patronsInfoSimpleMsg.getPatronsId());
                if(getPatronsReviveTimes(waitPatronData) >= config.getPatronsBuyMaxTimes()){
                    respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAME_REVIVE_PATRONS_MAX);
                    YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_REVIVE, respMsg);
                    CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                    return;
                }
                CrossRankUnionWarPatronData patronData = unionData.getMemberMap().get(patronsInfoSimpleMsg.getUserId()).getPatronDataMap(matchData.getTurn()).get(waitPatronData.getPatronId());
                int times = patronData.getBuyMap().getOrDefault(reqMsg.getGameNo(),0) + 1;
                int cost = config.getPatronsBuyTimeCost(times);
                costReviveCount = costReviveCount + cost;
            }
            if(costReviveCount > unionData.getDonateNum()){
                respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAME_REVIVE_ITEM_NOT_ENOUGH);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_REVIVE, respMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                return;
            }
            Map<Long, CrossRankUnionWarMemberData> memberDataMap = unionData.getMemberMap();
            long lifeTime = System.currentTimeMillis();
            for(RankUnionWarProto.RankUnionWarPatronsInfoSimpleMsg patronsInfoSimpleMsg : reqMsg.getPatronsInfosList()){
                logger.error("巅峰{}商会{}指导员{}复活玩家{}门客{}",getActivityId(),unionData.getUnionId(),userId,patronsInfoSimpleMsg.getUserId(),patronsInfoSimpleMsg.getPatronsId());
                CrossRankUnionWarWaitPatronData waitPatronData = waitPatronsMap.get(patronsInfoSimpleMsg.getUserId()).get(patronsInfoSimpleMsg.getPatronsId());
                CrossRankUnionWarPatronData patronData = memberDataMap.get(patronsInfoSimpleMsg.getUserId()).getPatronDataMap(matchData.getTurn()).get(waitPatronData.getPatronId());
                patronData.getBuyMap().put(reqMsg.getGameNo(),patronData.getBuyMap().getOrDefault(reqMsg.getGameNo(),0) + 1);
                addNeedSyncMatchCountList(matchData);
                //加锁和自动复活那边会并发
                //去判断下能不能复活
                joinRevivePatronToBattleLine(waitPatronData,matchData.getTurn(),lifeTime);

                int times = patronData.getBuyMap().getOrDefault(reqMsg.getGameNo(),0);
                CrossAutoLogMgr.add(new CrossRankUnionWarReviveLog(
                        getActivityId(), reqMsg.getGameNo(), unionData.getUnionId(), userId, reqMsg.getLine(), patronsInfoSimpleMsg.getUserId(),
                        patronsInfoSimpleMsg.getPatronsId(), times, config.getPatronsBuyTimeCost(times)));
            }
            unionData.setMemberMap(memberDataMap);
            unionData.setDonateNum(unionData.getDonateNum() - costReviveCount);
            recordDonateLineNum(unionData,matchData.getGameNo(),reqMsg.getLine(),costReviveCount);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_REVIVE, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
        }
    }

    //记录招募令的消耗信息
    private void recordDonateLineNum(CrossRankUnionWarUnionData unionData,int gameNo,int line,int num){
        Map<Integer, Map<Integer, Integer>> donateMap = unionData.getDonateMap();
        donateMap.get(gameNo).put(line,donateMap.get(gameNo).get(line) + num);
        unionData.setDonateMap(donateMap);
    }

    //查看招募令每条线用了多少
    public void recruitItemInfo(long serverId, long userId, RankUnionWarProto.RankUnionWarDonateInfoReqMsg reqMsg) {
        RankUnionWarProto.RankUnionWarRecruitItemInfoRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarRecruitItemInfoRespMsg.newBuilder();
        respMsg.setRet(0);
        CrossRankUnionWarUnionData unionData = getUnionData(userId);
        if(unionData == null){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_USER_CANNOT_PLAY);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_RECRUIT_INFO, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        Map<Integer, Map<Integer, Integer>> donateMap = unionData.getDonateMap();
        for(int gameNo : donateMap.keySet()){
            CrossRankUnionWarMatchData matchData = getGameNoMatch(gameNo);
            if(matchData == null)continue;
            RankUnionWarProto.RankUnionWarRecruitItemInfoMsg.Builder infoMsg = RankUnionWarProto.RankUnionWarRecruitItemInfoMsg.newBuilder();
            infoMsg.setSession(matchData.getTurn());
            infoMsg.setDivision(matchData.getDivision());
            for(int i=1;i<=5;i++){
                infoMsg.addNum(donateMap.get(gameNo).get(i));
            }
            respMsg.addInfos(infoMsg);
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_RECRUIT_INFO, respMsg);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
    }

    //排序门客信息
    public void patronsIndexInfo(long serverId, long userId, RankUnionWarProto.RankUnionWarPatronsIndexInfoReqMsg reqMsg) {
        RankUnionWarProto.RankUnionWarPatronsIndexInfoRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarPatronsIndexInfoRespMsg.newBuilder();
        respMsg.setRet(0);
        CrossRankUnionWarMatchData matchData = getIngGameNoMatch(reqMsg.getGameNo());
        if(matchData == null){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAME_OVER);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_INDEX_INFO, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        CrossRankUnionWarUnionData unionData = getUnionData(userId);

        if(unionData == null){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAME_OVER);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_INDEX_INFO, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        Map<Integer, Map<Integer, List<Long>>> opMap = unionData.getOpUserIdMap();
        if(opMap.containsKey(matchData.getGameNo())){
            boolean change = false;
            Map<Integer,Long> onlyOneMap = new ConcurrentHashMap<>();
            Map<Integer,List<Long>> lineUserIdMap = opMap.get(matchData.getGameNo());
            for(int line : lineUserIdMap.keySet()){
                boolean needRemove = false;
                for(long opUserId : lineUserIdMap.get(line)){
                    CrossRankUnionWarMemberData memberInfo = unionData.getMemberMap().get(opUserId);
                    if(memberInfo.getPosition() == eUnionPosition.Master.getValue() || memberInfo.getPosition() == eUnionPosition.DeputyMaster.getValue())continue;
                    if(!onlyOneMap.containsKey(line)){
                        onlyOneMap.put(line,userId);
                    }else{
//                        lineUserIdMap.get(line).remove(userId);
                        needRemove=true;
                        change = true;
                    }
                }
                if (needRemove){
                    lineUserIdMap.get(line).remove(userId);
                }
            }
            if(change){
                logger.error("巅峰商会战{}出现多个指挥官的{}",getActivityId(),unionData.getUnionId());
                unionData.setOpUserIdMap(opMap);
            }
        }
        for(CrossRankUnionWarMemberData memberData : unionData.getMemberMap().values()){
            if(isCommander(matchData.getGameNo(),reqMsg.getLine(),memberData.getUserId())){
                if(!memberData.isQuit()){
                    respMsg.addUserId(memberData.getUserId());
                }
            }
        }
        for(long memberUserId : unionData.getMemberMap().keySet()){
            if(!matchData.getWaitPatronsMap().containsKey(memberUserId))continue;
            for(CrossRankUnionWarWaitPatronData waitPatronData : matchData.getWaitPatronsMap().get(memberUserId).values()){
                if(!unionData.getMemberMap().containsKey(waitPatronData.getUserId()))continue;
                CrossRankUnionWarMemberData memberData = unionData.getMemberMap().get(waitPatronData.getUserId());
                if(waitPatronData.getLine() == reqMsg.getLine()){
                    RankUnionWarProto.RankUnionWarIndexPatronsInfoMsg.Builder pMsg = RankUnionWarProto.RankUnionWarIndexPatronsInfoMsg.newBuilder();
                    pMsg.setUserId(waitPatronData.getUserId());
                    UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(waitPatronData.getUserId());
                    if(userBaseInfo == null)continue;
                    pMsg.setNickName(userBaseInfo.getNickName());
                    pMsg.setIndex(waitPatronData.getLineIndex());
                    pMsg.setPatronsId(waitPatronData.getPatronId());
                    if(true || memberData.getPatronsSkillAdd() != 0){
                        BigInteger value = waitPatronData.getEarnSpeed();
                        value = value.multiply(BigInteger.valueOf(1000 + memberData.getPatronsSkillAdd()))
                                .divide(BigInteger.valueOf(1000));
                        pMsg.setEarnSpeed(value.toString());
                    }else{
                        pMsg.setEarnSpeed(waitPatronData.getEarnSpeed().toString());
                    }
                    pMsg.setSkinId(waitPatronData.getSkinId());
                    pMsg.setPromotionId(waitPatronData.getPromotionId());
                    pMsg.setLine(waitPatronData.getLine());
                    respMsg.addPatrons(pMsg);
                }
            }
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_INDEX_INFO, respMsg);
        CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
    }

    //排序门客
    public void patronsIndex(long serverId, long userId, RankUnionWarProto.RankUnionWarIndexPatronsReqMsg reqMsg) {
        RankUnionWarProto.RankUnionWarIndexPatronsRespMsg.Builder respMsg = RankUnionWarProto.RankUnionWarIndexPatronsRespMsg.newBuilder();
        respMsg.setRet(0);
//        respMsg.setIsCommander(isCommander(reqMsg.getGameNo(),reqMsg.getLine(),userId));
        CrossRankUnionWarMatchData matchData = getIngGameNoMatch(reqMsg.getGameNo());
        if(matchData == null || matchData.getStatus() != 0){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAME_NOT_PREPARE);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_INDEX, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        CrossRankUnionWarUnionData unionData = getUnionData(userId);
        if(unionData == null){
            respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_USER_CANNOT_PLAY);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_INDEX, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
            return;
        }
        for(CrossRankUnionWarMemberData memberData : unionData.getMemberMap().values()){
            if(isCommander(matchData.getGameNo(),reqMsg.getLine(),memberData.getUserId())){
                if(!memberData.isQuit()){
                    respMsg.addUserId(memberData.getUserId());
                }
            }
        }
        synchronized (unionData){
            Map<Long, Map<Integer, CrossRankUnionWarWaitPatronData>> waitPatronsMap = new ConcurrentHashMap<>(matchData.getWaitPatronsMap());
            Map<String, List<CrossRankUnionWarWaitPatronData>> readyPatronsMap = matchData.getReadyPatronsSortMap().get(reqMsg.getLine());
            List<CrossRankUnionWarWaitPatronData> readyPatronsList = readyPatronsMap.get(unionData.getUnionId());
            if(!isCommander(reqMsg.getGameNo(),reqMsg.getLine(),userId)){
                for(RankUnionWarProto.RankUnionWarIndexPatronsInfoMsg.Builder a : parseIndexPatronsInfoList(readyPatronsList)){
                    respMsg.addPatrons(a);
                }
                respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAME_NOT_COMMANDER);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_INDEX, respMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                return;
            }
            if(readyPatronsList.size() != reqMsg.getPatronsCount()){
                for(RankUnionWarProto.RankUnionWarIndexPatronsInfoMsg.Builder a : parseIndexPatronsInfoList(readyPatronsList)){
                    respMsg.addPatrons(a);
                }
                respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAME_INDEX_PATRONS_CHANGE);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_INDEX, respMsg);
                CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                return;
            }
            //两个兑换或者全部兑换
            for(int index = 0;index <  reqMsg.getPatronsCount() ; index++){
                RankUnionWarProto.RankUnionWarPatronsInfoSimpleMsg patronsMsg = reqMsg.getPatrons(index);
                if(!waitPatronsMap.containsKey(patronsMsg.getUserId())
                        || !waitPatronsMap.get(patronsMsg.getUserId()).containsKey(patronsMsg.getPatronsId())){
                    for(RankUnionWarProto.RankUnionWarIndexPatronsInfoMsg.Builder a : parseIndexPatronsInfoList(readyPatronsList)){
                        respMsg.addPatrons(a);
                    }
                    respMsg.setRet(GameErrorCode.E_RANKUNIONWAR_GAME_INDEX_PATRONS_CHANGE);
                    YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_INDEX, respMsg);
                    CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
                    return;
                }
            }
            for(int index = 0;index <  reqMsg.getPatronsCount() ; index++){
                RankUnionWarProto.RankUnionWarPatronsInfoSimpleMsg patronsMsg = reqMsg.getPatrons(index);
                CrossRankUnionWarWaitPatronData waitPatronData = waitPatronsMap.get(patronsMsg.getUserId()).get(patronsMsg.getPatronsId());
                waitPatronData.setLineIndex(index + 1);
                addNeedUpdateWaitPatrons(waitPatronData);
            }
            for(RankUnionWarProto.RankUnionWarIndexPatronsInfoMsg.Builder a : parseIndexPatronsInfoList(readyPatronsList)){
                respMsg.addPatrons(a);
            }
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_RANKUNIONWAR_PATRONS_INDEX, respMsg);
            CrossRankUnionWarDebugMgr.sendMessageDebug(getActivityId(),serverId, userId, pbMsg);
        }
    }

    private List<RankUnionWarProto.RankUnionWarIndexPatronsInfoMsg.Builder> parseIndexPatronsInfoList(List<CrossRankUnionWarWaitPatronData> patronDataList){
        List<RankUnionWarProto.RankUnionWarIndexPatronsInfoMsg.Builder> retList = new ArrayList<>();
        for(CrossRankUnionWarWaitPatronData warBattlePatronData : patronDataList){
            RankUnionWarProto.RankUnionWarIndexPatronsInfoMsg.Builder pMsg = RankUnionWarProto.RankUnionWarIndexPatronsInfoMsg.newBuilder();
            pMsg.setUserId(warBattlePatronData.getUserId());
            UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(warBattlePatronData.getUserId());
            if(userBaseInfo == null)continue;
            pMsg.setNickName(userBaseInfo.getNickName());
            pMsg.setIndex(warBattlePatronData.getLineIndex());
            pMsg.setPatronsId(warBattlePatronData.getPatronId());
            pMsg.setEarnSpeed(warBattlePatronData.getEarnSpeed().toString());
            pMsg.setSkinId(warBattlePatronData.getSkinId());
            pMsg.setPromotionId(warBattlePatronData.getPromotionId());
            pMsg.setLine(warBattlePatronData.getLine());
            retList.add(pMsg);
        }
        return retList;
    }




    private void addNeedInsertMatch(CrossRankUnionWarMatchData match){
        synchronized (needInsertMatchList){
            if(!needInsertMatchList.contains(match)){
                needInsertMatchList.add(match);
            }
        }
    }

    private void addNeedUpdateMatch(CrossRankUnionWarMatchData match){
        synchronized (needUpdateMatchList){
            if(!needUpdateMatchList.contains(match)){
                needUpdateMatchList.add(match);
            }
        }
    }

    private void addNeedInsertLine(CrossRankUnionWarLineData line){
        synchronized (needInsertLineList){
            if(!needInsertLineList.contains(line)){
                needInsertLineList.add(line);
            }
        }
    }

    private void addNeedUpdateLine(CrossRankUnionWarLineData line){
        synchronized (needUpdateLineList){
            if(!needUpdateLineList.contains(line)){
                needUpdateLineList.add(line);
            }
        }
    }
    private void addNeedInsertWaitPatrons(CrossRankUnionWarWaitPatronData waitPatron){
        synchronized (needInsertWaitPatronsList){
            if(!needInsertWaitPatronsList.contains(waitPatron)){
                needInsertWaitPatronsList.add(waitPatron);
            }
        }
    }

    private void addNeedUpdateWaitPatrons(CrossRankUnionWarWaitPatronData waitPatron){
        synchronized (needUpdateWaitPatronsList){
            if(!needUpdateWaitPatronsList.contains(waitPatron)){
                needUpdateWaitPatronsList.add(waitPatron);
            }
        }
    }

    private void addNeedDelWaitPatrons(CrossRankUnionWarWaitPatronData waitPatron){
        synchronized (needDelWaitPatronsList){
            if(!needDelWaitPatronsList.contains(waitPatron)){
                needDelWaitPatronsList.add(waitPatron);
            }
        }
    }

    private void addNeedInsertBattlePatrons(CrossRankUnionWarBattlePatronData battlePatron){
        synchronized (needInsertBattlePatronsList){
            if(!needInsertBattlePatronsList.contains(battlePatron)){
                needInsertBattlePatronsList.add(battlePatron);
            }
        }
    }

    private void addNeedUpdateBattlePatrons(CrossRankUnionWarBattlePatronData battlePatron){
        synchronized (needUpdateBattlePatronsList){
            if(!needUpdateBattlePatronsList.contains(battlePatron)){
                needUpdateBattlePatronsList.add(battlePatron);
            }
        }
    }

    private void addNeedInsertGamble(CrossRankUnionWarGambleData gamble){
        synchronized (needInsertGambleList){
            if(!needInsertGambleList.contains(gamble)){
                needInsertGambleList.add(gamble);
            }
        }
    }

    private void addNeedUpdateGamble(CrossRankUnionWarGambleData gamble){
        synchronized (needUpdateGambleList){
            if(!needUpdateGambleList.contains(gamble)){
                needUpdateGambleList.add(gamble);
            }
        }
    }

    private void addNeedInsertUserLock(CrossRankUnionWarUserLockData lockData){
        synchronized (needInsertUserLockList){
            if(!needInsertUserLockList.contains(lockData)){
                needInsertUserLockList.add(lockData);
            }
        }
    }

    private void addNeedUpdateUserLock(CrossRankUnionWarUserLockData lockData){
        synchronized (needUpdateUserLockList){
            if(!needUpdateUserLockList.contains(lockData)){
                needUpdateUserLockList.add(lockData);
            }
        }
    }

    private void addNeedInsertBarrage(CrossRankUnionWarBarrageData data){
        synchronized (needInsertBarrageList){
            if(!needInsertBarrageList.contains(data)){
                needInsertBarrageList.add(data);
            }
        }
    }

    private void addNeedUpdateBarrage(CrossRankUnionWarBarrageData data){
        synchronized (needUpdateBarrageList){
            if(!needUpdateBarrageList.contains(data)){
                needUpdateBarrageList.add(data);
            }
        }
    }


    public boolean save() {
        if (crossRankUnionWarData.isInsertOption()) {
            RankUnionWarBusiness.addCrossRankUnionWarData(crossRankUnionWarData);
        } else if (crossRankUnionWarData.isUpdateOption()) {
            RankUnionWarBusiness.updateCrossRankUnionWarData(crossRankUnionWarData);
        }
        for(CrossRankUnionWarUnionData unionData : unionDataMap.values()){
            if (unionData.isInsertOption()) {
                RankUnionWarBusiness.addCrossRankUnionWarUnionData(unionData);
            } else if (unionData.isUpdateOption()) {
                RankUnionWarBusiness.updateCrossRankUnionUnionWarData(unionData);
            }
        }
        List<CrossRankUnionWarMatchData> tempNeedInsertMatchList = new ArrayList<>();
        synchronized (needInsertMatchList){
            if(needInsertMatchList.size() > 0){
                tempNeedInsertMatchList = new ArrayList<>(needInsertMatchList);
                needInsertMatchList.clear();
            }
        }
        if(tempNeedInsertMatchList.size() > 0){
            RankUnionWarBusiness.addMatchList(tempNeedInsertMatchList);
        }
        List<CrossRankUnionWarMatchData> tempNeedUpdateMatchList = new ArrayList<>();
        synchronized (needUpdateMatchList){
            if(needUpdateMatchList.size() > 0){
                tempNeedUpdateMatchList = new ArrayList<>(needUpdateMatchList);
                needUpdateMatchList.clear();
            }
        }
        if(tempNeedUpdateMatchList.size() > 0){
            RankUnionWarBusiness.updateMatchList(tempNeedUpdateMatchList);
        }

        List<CrossRankUnionWarLineData> tempNeedInsertLineList = new ArrayList<>();
        synchronized (needInsertLineList){
            if(needInsertLineList.size() > 0){
                tempNeedInsertLineList = new ArrayList<>(needInsertLineList);
                needInsertLineList.clear();
            }
        }
        if(tempNeedInsertLineList.size() > 0){
            RankUnionWarBusiness.addLineList(tempNeedInsertLineList);
        }
        List<CrossRankUnionWarLineData> tempNeedUpdateLineList = new ArrayList<>();
        synchronized (needUpdateLineList){
            if(needUpdateLineList.size() > 0){
                tempNeedUpdateLineList = new ArrayList<>(needUpdateLineList);
                needUpdateLineList.clear();
            }
        }
        if(tempNeedUpdateLineList.size() > 0){
            RankUnionWarBusiness.updateLineList(tempNeedUpdateLineList);
        }
        //删除玩家退出商会门客数据
        List<CrossRankUnionWarWaitPatronData> tempNeedDelWaitPatronsList = new ArrayList<>();
        synchronized (needDelWaitPatronsList){
            if(needDelWaitPatronsList.size() > 0){
                tempNeedDelWaitPatronsList = new ArrayList<>(needDelWaitPatronsList);
                needDelWaitPatronsList.clear();
            }
        }
        if(tempNeedDelWaitPatronsList.size() > 0){
            RankUnionWarBusiness.delWaitPatronsList(tempNeedDelWaitPatronsList);
        }

        List<CrossRankUnionWarWaitPatronData> tempNeedInsertWaitPatronsList = new ArrayList<>();
        synchronized (needInsertWaitPatronsList){
            if(needInsertWaitPatronsList.size() > 0){
                tempNeedInsertWaitPatronsList = new ArrayList<>(needInsertWaitPatronsList);
                needInsertWaitPatronsList.clear();
            }
        }
        if(tempNeedInsertWaitPatronsList.size() > 0){
            RankUnionWarBusiness.addWaitPatronsList(tempNeedInsertWaitPatronsList);
        }
        List<CrossRankUnionWarWaitPatronData> tempNeedUpdateWaitPatronsList = new ArrayList<>();
        synchronized (needUpdateWaitPatronsList){
            if(needUpdateWaitPatronsList.size() > 0){
                tempNeedUpdateWaitPatronsList = new ArrayList<>(needUpdateWaitPatronsList);
                needUpdateWaitPatronsList.clear();
            }
        }
        if(tempNeedUpdateWaitPatronsList.size() > 0){
            RankUnionWarBusiness.updateWaitPatronsList(tempNeedUpdateWaitPatronsList);
        }

        List<CrossRankUnionWarBattlePatronData> tempNeedInsertBattlePatronsList = new ArrayList<>();
        synchronized (needInsertBattlePatronsList){
            if(needInsertBattlePatronsList.size() > 0){
                tempNeedInsertBattlePatronsList = new ArrayList<>(needInsertBattlePatronsList);
                needInsertBattlePatronsList.clear();
            }
        }
        if(tempNeedInsertBattlePatronsList.size() > 0){
            RankUnionWarBusiness.addBattlePatronsList(tempNeedInsertBattlePatronsList);
        }
        List<CrossRankUnionWarBattlePatronData> tempNeedUpdateBattlePatronsList = new ArrayList<>();
        synchronized (needUpdateBattlePatronsList){
            if(needUpdateBattlePatronsList.size() > 0){
                tempNeedUpdateBattlePatronsList = new ArrayList<>(needUpdateBattlePatronsList);
                needUpdateBattlePatronsList.clear();
            }
        }
        if(tempNeedUpdateBattlePatronsList.size() > 0){
            RankUnionWarBusiness.updateBattlePatronsList(tempNeedUpdateBattlePatronsList);
        }

        List<CrossRankUnionWarGambleData> tempNeedInsertGambleList = new ArrayList<>();
        synchronized (needInsertGambleList){
            if(needInsertGambleList.size() > 0){
                tempNeedInsertGambleList = new ArrayList<>(needInsertGambleList);
                needInsertGambleList.clear();
            }
        }
        if(tempNeedInsertGambleList.size() > 0){
            RankUnionWarBusiness.addGambleList(tempNeedInsertGambleList);
        }
        List<CrossRankUnionWarGambleData> tempNeedUpdateGambleList = new ArrayList<>();
        synchronized (needUpdateGambleList){
            if(needUpdateGambleList.size() > 0){
                tempNeedUpdateGambleList = new ArrayList<>(needUpdateGambleList);
                needUpdateGambleList.clear();
            }
        }
        if(tempNeedUpdateGambleList.size() > 0){
            RankUnionWarBusiness.updateGambleList(tempNeedUpdateGambleList);
        }


        List<CrossRankUnionWarUserLockData> tempNeedInsertUserLockList = new ArrayList<>();
        synchronized (needInsertUserLockList){
            if(needInsertUserLockList.size() > 0){
                tempNeedInsertUserLockList = new ArrayList<>(needInsertUserLockList);
                needInsertUserLockList.clear();
            }
        }
        if(tempNeedInsertUserLockList.size() > 0){
            RankUnionWarBusiness.addUserLockList(tempNeedInsertUserLockList);
        }
        List<CrossRankUnionWarUserLockData> tempNeedUpdateUserLockList = new ArrayList<>();
        synchronized (needUpdateUserLockList){
            if(needUpdateUserLockList.size() > 0){
                tempNeedUpdateUserLockList = new ArrayList<>(needUpdateUserLockList);
                needUpdateUserLockList.clear();
            }
        }
        if(tempNeedUpdateUserLockList.size() > 0){
            RankUnionWarBusiness.updateUserLockList(tempNeedUpdateUserLockList);
        }

        List<CrossRankUnionWarBarrageData> tempNeedInsertBarrageList = new ArrayList<>();
        synchronized (needInsertBarrageList){
            if(needInsertBarrageList.size() > 0){
                tempNeedInsertBarrageList = new ArrayList<>(needInsertBarrageList);
                needInsertBarrageList.clear();
            }
        }
        if(tempNeedInsertBarrageList.size() > 0){
            RankUnionWarBusiness.addBarrageList(tempNeedInsertBarrageList);
        }
        return true;
    }
}
